Why Double.NaN==Double.NaN is false

This is taken from the top two answers Why does Double.NaN==Double.NaN return false?

Question

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?

Answer

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.

Java Language Specification (JLS) says:
Floating-point operators produce no exceptions (§11). 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 returns true, including x!=x when x is NaN. 

Comments

  1. To compare Double.NaN, you should ALWAYS use the Double.isNaN(double v) method:

    http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#isNaN%28double%29

    Same for Float.isNaN(float v). For more info about Java NaN, see:

    http://ppkwok.blogspot.co.uk/2012/11/java-cafe-1-never-write-nan-nan_24.html

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues