language-agnosticfloating-pointprecisionieee-754signedness

For any finite floating point value, is it guaranteed that x - x == 0?


Floating point values are inexact, which is why we should rarely use strict numerical equality in comparisons. For example, in Java this prints false (as seen on ideone.com):

System.out.println(.1 + .2 == .3);
// false

Usually the correct way to compare results of floating point calculations is to see if the absolute difference against some expected value is less than some tolerated epsilon.

System.out.println(Math.abs(.1 + .2 - .3) < .00000000000001);
// true

The question is about whether or not some operations can yield exact result. We know that for any non-finite floating point value x (i.e. either NaN or an infinity), x - x is ALWAYS NaN.

But if x is finite, is any of this guaranteed?

  1. x * -1 == -x
  2. x - x == 0

(In particular I'm most interested in Java behavior, but discussions for other languages are also welcome.)


For what it's worth, I think (and I may be wrong here) the answer is YES! I think it boils down to whether or not for any finite IEEE-754 floating point value, its additive inverse is always computable exactly. Since e.g. float and double has one dedicated bit just for the sign, this seems to be the case, since it only needs flipping of the sign bit to find the additive inverse (i.e. the significand should be left intact).

Related questions


Solution

  • Although x - x may give you -0 rather than true 0, -0 compares as equal to 0, so you will be safe with your assumption that any finite number minus itself will compare equal to zero.

    See Is there a floating point value of x, for which x-x == 0 is false? for more details.