I was just studying OCPJP questions and I found this strange code:
public static void main(String a[]) {
System.out.println(Double.NaN==Double.NaN);
System.out.println(Double.NaN!=Double.NaN);
}
When I ran the code, I got:
false
true
How is the output false
when we're comparing two things that look the same as each other? What does NaN
mean?
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
Java treats all NaN as quiet NaN.
NaN means "Not a Number".
Java Language Specification (JLS) Third Edition says:
The javadoc for Double.NaN says it all:
Interestingly, the source for
Double
definesNaN
thus:The special behaviour you describe is hard-wired into the JVM.
Not a number represents the result of operations whose result is not representable with a number. The most famous operation is 0/0, whose result is not known.
For this reason, NaN is not equal to anything (including other not-a-number values). For more info, just check the wikipedia page: http://en.wikipedia.org/wiki/NaN
as per, The IEEE standard for floating point arithmetic for Double Precision numbers,
where,
Which means,
If all
E
bits are 1, and if there is any non-zero bit inF
then the number isNaN
.therefore, among others, all following numbers are
NaN
,In particular, you cannot test
to check whether a particular result equals
Double.NaN
, because all “not a number” values are considered distinct. However, you can use theDouble.isNaN
method:It might not be a direct answer to the question. But if you want to check if something is equal to
Double.NaN
you should use this:This will return
true