The correct answer is a simple "because the standard (and the docs) say so". But I'm not gonna be cynical because it's obvious that's not what you are after.
In addition to the other answers here, I'll try to relate the infinities to saturating arithmetic.
Other answers have already stated that the reason the comparisons on NaNs result in true
, so I'm not gonna beat a dead horse.
Let's say I have a saturating integer that represents grayscale colors. Why am I using saturating arithmetic? Because anything brighter than white is still white, and anything darker than black is still black (except orange). That means BLACK - x == BLACK
and WHITE + x == WHITE
. Makes sense?
Now, let's say we want to represent those grayscale colors with a (signed) 1s complement 8-bit integer where BLACK == -127
and WHITE == 127
. Why 1s complement? Because it gives us a signed zero like IEEE 754 floating point. And, because we are using saturating arithmetic, -127 - x == -127
and 127 + x == 127
.
How does this relate to floating point infinities? Replace the integer with floating point, BLACK
with NEGATIVE_INFINITY
, and WHITE
with POSITIVE_INFINITY
and what do you get? NEGATIVE_INFINITY - x == NEGATIVE_INFINITY
and POSITIVE_INFINITY + x == POSITIVE_INFINITY
.
Since you used POSITIVE_INFINITY
, I'll use it also. First we need a class to represent our saturating integer-based color; let's call it SaturatedColor
and assume it works like any other integer in Java. Now, let's take your code and replace double
with our own SaturatedColor
and Double.POSITIVE_INFINITY
with SaturatedColor.WHITE
:
SaturatedColor a = SaturatedColor.WHITE;
SaturatedColor b = SaturatedColor.WHITE;
As we established above, SaturatedColor.WHITE
(just WHITE
above) is 127
, so let's do that here:
SaturatedColor a = 127;
SaturatedColor b = 127;
Now we take the System.out.println
statements you used and replace a
and b
with their value (values?):
System.out.println(127 == 127);
System.out.println(127 < 127);
System.out.println(127 > 127);
It should be obvious what this will print.