Why does Double.NaN==Double.NaN return false?
Solution 1:
NaN means "Not a Number".
Java Language Specification (JLS) Third Edition says:
An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns
false
and any!=
comparison involving NaN returnstrue
, includingx!=x
whenx
is NaN.
Solution 2:
NaN is by definition not equal to any number including NaN. This is part of the IEEE 754 standard and implemented by the CPU/FPU. It is not something the JVM has to add any logic to support.
http://en.wikipedia.org/wiki/NaN
A comparison with a NaN always returns an unordered result even when comparing with itself. ... The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
Java treats all NaN as quiet NaN.