Why does adding a small float to a large float just drop the small one?

后端 未结 3 409
南笙
南笙 2020-11-29 12:13

Say I have:

float a = 3            // (gdb) p/f a   = 3
float b = 299792458    // (gdb) p/f b   = 299792448

then

float sum          


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 13:05

    32-bit floats only have 24 bits of precision. Thus, a float cannot hold b exactly - it does the best job it can by setting some exponent and then mantissa to get as close as possible.

    When you then consider the floating point representation of b and a, and try and add them, the addition operation will shift the small number a's mantissa downwards as it tries to match b's exponent, to the point where the value (3) falls off the end and you're left with 0. Hence, the addition operator ends up adding floating point zero to b.

提交回复
热议问题