简体   繁体   English

C语言中float的幅度范围?

[英]Range of magnitude for float in c programming language?

In The C Programming Language book by Dennis Ritchie, it is mentioned that "A float number is typically a 32-bit quantity, with at least six significant digits and magnitude generally between about 10^-38 and 10^+38." 在Dennis Ritchie的C编程语言书中,提到“浮点数通常是32位的数量,至少有六个有效数字,其大小通常在10 ^ -38到10 ^ + 38之间。”

How is that possible since we have only 32-bits? 由于我们只有32位,这怎么可能? Shouldn't the top limit be 2^32? 上限不应该是2 ^ 32吗? I tried printing out a float by looping and multiplying a float by 10, 38 times and this was the output 100000006944061730000000000000000000000.000000 . 我尝试通过将浮点数乘以10、38次来打印出浮点数,这就是输出1000000069440617300000000000000000000000000.000000。 It also has to keep track of the sign , so how is it storing all this in just 32-bits? 它还必须跟踪符号,那么如何将其全部存储为32位呢?

See Single-precision floating-point format for a details about a typical C float . 有关典型C float的详细信息,请参见单精度浮点格式

Range of magnitude for float in c programming language? C语言中float的幅度范围?

#include <float.h>
printf("float magnitude range %e to %e\n", FLT_MIN, FLT_MAX);
// typical result
// float magnitude range 1.175494e-38 to 3.402823e+38

How is that possible since we have only 32-bits? 由于我们只有32位,这怎么可能?

Typical float does indeed only store about 2 32 different values. 实际上,典型的float确实只存储大约2 32个不同的值。 Yet they are not distributed linearly but logarithmically in linear groups. 但是它们不是线性分布而是线性对数分布。

2 23 different values in the range [2 -126 to 2 -127 ) 2 [ 23 -126到2 -127的范围内的23个不同的值
... ...
2 23 different values in the range [0.5 to 1.0) 2 23个在[0.5至1.0)范围内的不同值
2 23 different values in the range [1.0 to 2.0) 2 23个在[1.0到2.0]范围内的不同值
2 23 different values in the range [2.0 to 4.0) 2 23个在[2.0到4.0)范围内的不同值
... ...
2 23 different values in the range [2 127 to 2 128 ) 2 23个在[ 21272128 ]范围内的不同值

And their negative counter parts. 以及它们的负面反面部分。
Also +/- zeros, small sub-normal numbers, +/- infinity and Not-a-Number 还有+/-零,较小的次正规数,+ /-无限大和非数字

It also has to keep track of the sign , so how is it storing all this in just 32-bits? 它还必须跟踪符号,那么如何将其全部存储为32位呢?

 1 bit for sign
 8 bits for the binary exponent
23 bits for the significant (with a MSBit usually implied as 1)
--
32 bits

When printing a float , only about 6 or so ( FLT_DIG, FLT_DECIMAL_DIG ) significant digits usually are important. 当打印float ,通常只有大约6个左右( FLT_DIG, FLT_DECIMAL_DIG )的有效数字很重要。

printf("%.*e\n", FLT_DIG-1, FLT_TRUE_MIN);
printf("%.*e\n", FLT_DIG-1, FLT_MIN);
printf("%.*e\n", FLT_DIG-1, acos(-1));
printf("%.*e\n", FLT_DECIMAL_DIG - 1, nextafterf(FLT_MAX, 0.0));
printf("%.*e\n", FLT_DECIMAL_DIG - 1, FLT_MAX);

Output 产量

1.40130e-45    // min sub-normal
1.17549e-38    // min normal
3.14159e+00    // pi
3.40282326e+38 // number before max
3.40282347e+38 // max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM