Why do floating-point numbers have signed zeros?

-0 is (generally) treated as 0 *******. It can result when a negative floating-point number is so close to zero that it can be considered 0 (to be clear, I’m referring to arithmetic underflow, and the results of the following computations are interpreted as being exactly ±0, not just really small numbers). e.g.

System.out.println(-1 / Float.POSITIVE_INFINITY);
-0.0

If we consider the same case with a positive number, we will receive our good old 0:

System.out.println(1 / Float.POSITIVE_INFINITY);
0.0

******* Here’s a case where using -0.0 results in something different than when using 0.0:

System.out.println(1 / 0.0);
System.out.println(1 / -0.0);
Infinity
-Infinity

This makes sense if we consider the function 1 / x. As x approaches 0 from the +-side, we should get positive infinity, but as it approaches from the --side, we should get negative infinity. The graph of the function should make this clear:

(source)

In math-terms:

enter image description here

enter image description here

This illustrates one significant difference between 0 and -0 in the computational sense.


Here are some relevant resources, some of which have been brought up already. I’ve included them for the sake of completeness:

Leave a Comment