Why does Double.NaN==Double.NaN return false?
Asked Answered
J

10

162

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?

Jonas answered 11/1, 2012 at 13:2 Comment(9)
This is really weird. Because Double.NaN is static final, the comparision with == should return true. +1 for the question.Groundnut
The same is true in python: In [1]: NaN==NaN Out[1]: FalseBast
The same is true in all languages that correctly follow the IEEE 754 standard.Consumerism
Intuition: "Hello" is not a number, true (boolean) is also not a number. NaN != NaN for the same reason "Hello" != trueEverick
@kevin But when I am doing Double.compare(Double.NaN, Double.NaN) I am getting 0 as output i.e both are equalJonas
@Stephan: The comparison with Double.NaN==Double.NaN should indeed return true if Double.NaN were of type java.lang.Double. However, its type is the primitive double, and the operator rules for double apply (which demand this inequality for conformance with IEEE 754, as explained in the answers).Garage
@RaviKumar: Yes, that is indeed a bit inconsistent. However, it's explicitly documented in the Javadocs: "Double.NaN is considered by this method to be equal to itself " (see file:///C:/Users/sle/Downloads/Docs/jdk-6u25-fcs-bin-b04-apidocs-04_Apr_2011/docs/api/java/lang/Double.html#compareTo%28java.lang.Double%29 )Garage
See also Why is undefined == undefined but NaN != NaN? and is NaN equals to NaN (these are about JS, but as noted both above and below, this is language-independent).Significative
@Everick but: String h = "Hello"; // not a number assertFalse(h != h); // is false Double.NaN behaviour certainly ain't intuitive...Statehood
K
142

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.

Kyla answered 11/1, 2012 at 13:6 Comment(2)
@nibot: Mostly true. Any comparison with an IEEE-conforming float will produce false. So that standard differs from Java in that IEEE demands that (NAN != NAN) == false.Germain
Opening up this Pandora's box - where do you see that "IEEE demands that (NAN != NAN) == false"?Keel
S
62

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.

Scorper answered 11/1, 2012 at 14:4 Comment(3)
Is it implemented by the CPU, or is it hard-wired in the JVM as Bohemian mentions?Infare
The JVM has to call whatever will implement it correctly. On a PC, the CPU does all the work as such. On a machine without this support the JVM has to implement it. (I don't know of any such machine)Scorper
Back in the day when the 8087 was an option, the C library contained an FP emulator. Programs like the JVM wouldn't have to worry about it either way.Bini
G
51

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);
Grammarian answered 11/1, 2012 at 13:35 Comment(14)
Do you know of any case where having NaN != NaN be false would make programs more complicated than having NaN != NaN be true? I know IEEE made the decision ages ago, but from a practical perspective, I've never seen cases where it's useful. If an operation is supposed to run until consecutive iterations yield the same result, having two consecutive iterations yield NaN would be "naturally" detected as an exit condition were it not for that behavior.Pursy
@Pursy How can you say that two random non number are naturally equal? Or say, primitively equal? Think of NaN as an instance, not something primitive. Each different abnormal result is a different instance of something strange and even if both should represent the same, using == for different instances must return false. On the other hand, when using equals it can be handled properly as you intend. [docs.oracle.com/javase/7/docs/api/java/lang/…Grammarian
@falsarella: The issue isn't whether two random numbers should be considered "definitely equal", but rather in what cases is it useful to have any number compare as "definitely unequal" to itself. If one is trying to compute the limit of f(f(f...f(x))), and one finds a y=f[n](x) for some n such that the result of f(y) is indistinguishable from y, then y will be indistinguishable from the result of any more-deeply-nested f(f(f(...f(y))). Even if one wanted NaN==NaN to be false, having Nan!=Nan also be false would be less "surprising" than having x!=x be true for some x.Pursy
@Pursy If you are playing with Double's (not double's) and you write a condition using == (which would be also strange not to use equals here), it means that you would be willing to execute the inner block when both sides are equal (obviously), and probably use tem (say, in an equation), so the less "surprising", for me, would be entering in my block when NaN = NaN and cause a surprisingly unexpected error! I don't have a showcase for you and probably just few people have passed through that problem. That is an OCPJP question and the point is to clarify and solve the OP's problem.Grammarian
@falsarella: I believe the type of Double.NaN is not Double, but double, so the question is one related to the behavior of double. Though there exist functions which can test for an equivalence relation involving double values, the only compelling answer I know of for "why" (which is part of the original question) is "because some people at the IEEE didn't think equality-testing should define an equivalence relation". BTW, is there any concise idiomatic way to test x and y for equivalence using only primitive-operators? All formulations I know of are rather clunky.Pursy
@Pursy maybe testing mathematical series for convergence? I think +/- inf would probably be used instead, but I can imagine a case where a series that diverges is represented using NaN, and two such series wouldn't necessarily be equalSubsidiary
@GoogieK: If a mathematical sequence is expected to converge but an iteration yields NaN, repeated iterations aren't apt to do much good. I would think that having NaN values compare as equal would cause most algorithms to announce in such a case that the sequence converged to NaN, while having them compare as unequal would cause the program to iterate forever absent a deliberate exit-test for NaN.Pursy
@Pursy The documentation also says, for example, that one of the reasons that equals returns true when comparing two NaN's, is that it will make hashtables to work properly.Grammarian
@falsarella: The equals method in Java tests if x is greater than y, or if it's less than y, and if neither condition applies it converts the 64 bits of each value to a long with the same pattern and examines the resulting values. Not particularly concise. If one accepts positive and negative zero as equivalent (IMHO, they shouldn't be, but a definition of equality which regarded them as equivalent would at least be an equivalence relation), (x >= y && x <= y) || (x != x && y != y) would probably be faster unless a particular Java implementation used a native implementation.Pursy
@Pursy I agree: it's faster. I just wanted to add that the behaviors are different.Grammarian
best and simple answer. Thank youRosenberry
Double.NaN.equals/compareTo is not valid code! Double.NaN is a double and you can't invoke method on it.Predict
Double.NaN.equals(Double.NaN): Did you mean Double.valueOf(...).equals(Double.valueOf(...)) ?Jamilajamill
That's the way. The Double instance equality will consider NaNs as equal.Grammarian
R
19

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

Radloff answered 1/10, 2015 at 14:8 Comment(0)
L
6

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.

Labiate answered 11/1, 2012 at 13:6 Comment(1)
Is it hard wired in the JVM, or is it implemented by the CPU as Peter mentions?Infare
E
4

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"
Environs answered 30/1, 2015 at 15:56 Comment(0)
E
3

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.

Excretory answered 11/1, 2012 at 13:4 Comment(0)
A
2

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

Ailbert answered 11/1, 2012 at 13:7 Comment(6)
-1: It does not represent the result of 0/0. 0/0 is always NaN, but NaN can be the result of other operations - such as 2+NaN: an operation that has no mathematically definite result produces NaN, as per the answer by @AdrianMitevOsy
Indeed, NaN stands for "Not a Number", and it is the result of all operations that have as result an undefined or unrepresentable value. The most famous and common operation is 0/0, but obviously there are tons of other operations that has the same result. I agree that my answer could be improved, but I disagree on the -1... I just checked that also wikipedia uses the 0/0 operations as the first example of operation with an NaN result (en.wikipedia.org/wiki/NaN).Ailbert
Also, this is in the Java source for Double: public static final double NaN = 0.0d / 0.0;Banderillero
@Ailbert +0, now that the false statement is gone. And my -1 or +1 are not for you to agree or disagree; but it is good to leave a comment with a -1, so that the author can understand why his answer is considered unuseful - and change it, if he so wishes.Osy
@Banderillero if that comment was meant for me, please rephrase it: I do not understand it.Osy
@Osy I agree that the goal is to give the best answer to the question. However, I think that there are several ways to explain the same thing. Additionally, I think that beginners can exploit a simple example of the phenomenon, and then they can re-elaborate on that.Ailbert
M
0

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".

Medardas answered 26/2, 2018 at 2:32 Comment(0)
T
0

if you have variable

Double a = Double.NaN

use

String.valueOf(Double.NaN) == a.toString()
Trypanosomiasis answered 30/1, 2021 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.