c编程语言中float的幅度范围?

时间:2017-04-07 17:44:19

标签: c floating-point

在Dennis Ritchie的C编程语言书中,提到“浮点数通常是32位数,至少有6位有效数字,幅度一般在10 ^ -38到10 ^ + 38之间。 “

这怎么可能,因为我们只有32位?上限不应该是2 ^ 32吗?我尝试通过循环并将浮点乘以10,38次来打印浮点数,这是输出100000006944061730000000000000000000000.000000。它还必须跟踪符号,那么它如何以32位的形式存储所有这些?

1 个答案:

答案 0 :(得分:3)

有关典型C float的详细信息,请参阅Single-precision floating-point format

  

c编程语言中浮点数的范围?

#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
  

这怎么可能,因为我们只有32位?

典型的float确实只存储了大约2个 32 个不同的值。然而,它们不是线性分布的,而是以线性组的形式对数分布。

2 23 范围[2 -126 至2 -127 )的不同值
...
2 23 在[0.5至1.0)范围内的不同值 2 23 在[1.0至2.0]范围内的不同值 2 23 在[2.0至4.0]范围内的不同值 ...
2 23 范围[2 127 至2 128 )的不同值

他们的反面部分 +/-零,小的正常数,+ / - 无穷大和非数字

  

它还必须跟踪符号,那么它如何以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

打印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);

输出

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