Behaviour of negative zero (-0.0) in comparison with positive zero (+0.0)

前端 未结 4 1719
夕颜
夕颜 2020-12-05 15:43

In my code,

float f = -0.0; // Negative 

and compared with negative zero

f == -0.0f

res

4条回答
  •  没有蜡笔的小新
    2020-12-05 16:11

    Floating point arithmetic in C++ is often IEEE-754. This norm differs from the mathematical definition of the real number set.

    This norm defines two different representations for the value zero: positive zero and negative zero. It is also defined that those two representations must compare equals, so by definition:

    +0.0 == -0.0
    

    As to why it is so, in its paper What Every Computer Scientist Should Know About Floating Point Arithmetic, David Goldberg, 1991-03 (linked in the IEEE-754 page on the IEEE website) writes:

    In IEEE arithmetic, it is natural to define log 0 = -∞ and log x to be a NaN when x < 0. Suppose that x represents a small negative number that has underflowed to zero. Thanks to signed zero, x will be negative, so log can return a NaN. However, if there were no signed zero, the log function could not distinguish an underflowed negative number from 0, and would therefore have to return -∞.

提交回复
热议问题