Why does Double.NaN==Double.NaN return false?

JavaFloating PointNanScjpOcpjp

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 returns true, including x!=x when x is NaN.

Solution 2 - Java

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.

Solution 3 - Java

Why that logic

NaN means Not a Number. What is not a number? Anything. You can have anything in one side and anything in the other side, so nothing guarantees that both are equals. NaN is calculated with Double.longBitsToDouble(0x7ff8000000000000L) and as you can see in the documentation of longBitsToDouble:

> If the argument is any value in the range 0x7ff0000000000001L through > 0x7fffffffffffffffL or in the range 0xfff0000000000001L through > 0xffffffffffffffffL, the result is a NaN.

Also, NaN is logically treated inside the API.


Documentation

/** 
 * A constant holding a Not-a-Number (NaN) value of type
 * {@code double}. It is equivalent to the value returned by
 * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
 */
public static final double NaN = 0.0d / 0.0;

By the way, NaN is tested as your code sample:

/**
 * Returns {@code true} if the specified number is a
 * Not-a-Number (NaN) value, {@code false} otherwise.
 *
 * @param   v   the value to be tested.
 * @return  {@code true} if the value of the argument is NaN;
 *          {@code false} otherwise.
 */
static public boolean isNaN(double v) {
    return (v != v);
}


Solution

What you can do is use compare/compareTo:

> Double.NaN is considered by this method to be equal to itself > and greater than all other double values (including > Double.POSITIVE_INFINITY).

Double.compare(Double.NaN, Double.NaN);
Double.NaN.compareTo(Double.NaN);

Or, equals:

> If this and argument both represent Double.NaN, then > the equals method returns true, even though > Double.NaN==Double.NaN has the value false.

Double.NaN.equals(Double.NaN);

Solution 4 - Java

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:

double d = Double.NaN
Double.isNaN(d);

This will return true

Solution 5 - Java

The javadoc for Double.NaN says it all:

> A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).

Interestingly, the source for Double defines NaN thus:

public static final double NaN = 0.0d / 0.0;

The special behaviour you describe is hard-wired into the JVM.

Solution 6 - Java

as per, The IEEE standard for floating point arithmetic for Double Precision numbers,

> The IEEE double precision floating point standard representation > requires a 64 bit word, which may be represented as numbered from 0 to > 63, left to right

enter image description here where,

S: Sign – 1 bit
E: Exponent – 11 bits
F: Fraction – 52 bits 

> If E=2047 (all E are 1) and F is nonzero, then V=NaN ("Not a number")

Which means,

If all E bits are 1, and if there is any non-zero bit in F then the number is NaN.

therefore, among others, all following numbers are NaN,

0 11111111 0000000000000000010000000000000000000000000000000000 = NaN
1 11111111 0000010000000000010001000000000000001000000000000000 = NaN
1 11111111 0000010000011000010001000000000000001000000000000000 = NaN

In particular, you cannot test

if (x == Double.NaN) 

to check whether a particular result equals Double.NaN, because all “not a number” values are considered distinct. However, you can use the Double.isNaN method:

if (Double.isNaN(x)) // check whether x is "not a number"

Solution 7 - Java

NaN is a special value that denotes "not a number"; it's the result of certain invalid arithmetic operations, such as sqrt(-1), and has the (sometimes annoying) property that NaN != NaN.

Solution 8 - Java

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

Solution 9 - Java

According to this link, it has various situations and difficult to remember. This is how I remember and distinguish them. NaN means "mathematically undefined" for example: "the result of 0 divided by 0 is undefined" and because it is undefined, so "comparison related to undefined is of course undefined". Besides, it works more like mathematical premises. On the other hand, both positive and negative infinite is predefined and definitive, for example "positive or negative infinite large is well defined mathematically".

Solution 10 - Java

if you have variable

Double a = Double.NaN

use

String.valueOf(Double.NaN) == a.toString()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaverickView Question on Stackoverflow
Solution 1 - JavaAdrian MitevView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavafalsarellaView Answer on Stackoverflow
Solution 4 - JavaJRENView Answer on Stackoverflow
Solution 5 - JavaBohemianView Answer on Stackoverflow
Solution 6 - JavaSufiyan GhoriView Answer on Stackoverflow
Solution 7 - JavaFred FooView Answer on Stackoverflow
Solution 8 - JavaMatteoView Answer on Stackoverflow
Solution 9 - JavaTiinaView Answer on Stackoverflow
Solution 10 - JavaElikoView Answer on Stackoverflow