Search code examples
floating-pointlanguage-agnosticieee-754

Floating-point subtractive identities


As I understand it, in IEEE floating point, the following identity really does always apply:

x - 0.0 == x

But the following mathematical identity may not necessarily always apply, due to issues regarding signed zero:

0.0 - x == -x

Is this correct?


Solution

  • (+0) − (+0) returns (−0) when rounding towards −∞, but (+0) in all other rounding modes. So replacing x - 0.0 with x will deliver bit-wise identical results only if the rounding mode towards −∞ ("down") is excluded. However, since (-0) and (+0) compare equal under IEEE-754 semantics, x - 0.0 == x will hold in all rounding modes.

    −(+0) results in (−0), whereas (+0) − (+0) returns (+0) in all rounding modes other than when rounding towards −∞. So replacing 0.0 - x with -x will deliver bit-wise identical results only when the rounding mode is towards −∞ ("down"). However, since (-0) and (+0) compare equal under IEEE-754 semantics, 0.0 -x == -x will hold in all rounding modes.

    As far as bit-wise equality (rather than floating-point equality comparison) is concerned, it should also be noted that in IEEE-754 (2008), the negate operation is (like the absolute value and copysign operations) defined in terms of bit string manipulation, and will therefore modify the "sign bit" of NaNs (see section 6.3 of the standard). On platforms that implement pass-through of NaN payloads, the results of negation and subtraction from zero therefore differ at bit level if x is a NaN.