简体   繁体   English

C中的浮点数与预期的略有不同

[英]floating point numbers in C slightly different from expected

I noticed that in C, a float can be as small as 2^-149, and as large as 2^127. 我注意到在C语言中,浮点数可小至2 ^ -149,大至2 ^ 127。 If I try to set the float to any smaller or larger respectively than these, then I get zero and inf, respectively. 如果我尝试将float分别设置为小于或小于这些值,则分别获得零和inf。 The 2^149 doesn't make sense to me; 2 ^ 149对我来说没有意义; where does it come from? 它从何而来?

It appears that the exponent is 8 bits, so we can have 2^-128 to 2^127. 看来指数是8位,所以我们可以有2 ^ -128到2 ^ 127。 The overall sign of the float is 1 bit, so that leaves 23 bits for the significand since a float is 32 bits total. 浮点数的总符号为1位,因此,由于浮点数总共为32位,因此有效位数保留了23位。 If all 23 bits of the significand are placed after the binary "decimal point" such that the significand is <= 0.5, then we should be able to have floats as small as 2^(-128-23) = 2^-151. 如果有效数字的所有23位都放置在二进制“小数点”之后,使得有效数字<= 0.5,则我们应该能够使浮点数小至2 ^(-128-23)= 2 ^ -151。 On the other hand, if one of the 23 bits is placed BEFORE the binary "decimal" point such that the significand is <= 1, then we would have the smallest float be 2^(-128-22) = 2^-150. 另一方面,如果将23位中的一个放置在二进制“十进制”点之前,使得有效位数<= 1,则最小浮点数将为2 ^(-128-22)= 2 ^ -150 。 Both of these do not agree with the fact that the smallest float seems to be 2^-149. 这两个都不同意最小浮点似乎是2 ^ -149的事实。 Why is this? 为什么是这样?

Infinity (+ or -) is represented by the maximum exponent (all 1 bits), and zero mantissa. 无穷大(+或-)由最大指数(全1位)和零尾数表示。 NaN is represented by the maximum exponent, and any non-zero mantissa. NaN用最大指数和任何非零尾数表示。

Denormal numbers, and zero, are represented with the minimum exponent (all 0 bits). 非正规数和零用最小指数(全0位)表示。

So those two exponents are not available for normal numbers. 因此,这两个指数不适用于正常数字。

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

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