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?

Pops
  • 30,199
  • 37
  • 136
  • 151
Maverick
  • 3,053
  • 6
  • 24
  • 30
  • 8
    This is really weird. Because Double.NaN is static final, the comparision with == should return true. +1 for the question. – Stephan Jan 11 '12 at 14:10
  • 2
    The same is true in python: `In [1]: NaN==NaN Out[1]: False` – tdc Jan 11 '12 at 15:29
  • 58
    The same is true in all languages that correctly follow the IEEE 754 standard. – zzzzBov Jan 11 '12 at 16:13
  • 4
    Intuition: "Hello" is not a number, true (boolean) is also not a number. NaN != NaN for the same reason "Hello" != true – Kevin Jan 12 '12 at 23:01
  • @kevin But when I am doing Double.compare(Double.NaN, Double.NaN) I am getting 0 as output i.e both are equal – Maverick Jan 13 '12 at 04:09
  • 3
    @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). – sleske Jan 13 '12 at 12:48
  • @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 ) – sleske Jan 13 '12 at 13:10
  • See also [Why is undefined == undefined but NaN != NaN?](http://stackoverflow.com/questions/7178175/why-is-undefined-undefined-but-nan-nan) and [is NaN equals to NaN](http://stackoverflow.com/questions/6976721/is-nan-equals-to-nan) (these are about JS, but as noted both above and below, this is language-independent). – Pops Jan 13 '12 at 14:21
  • @Kevin but: `String h = "Hello"; // not a number` `assertFalse(h != h); // is false` Double.NaN behaviour certainly ain't intuitive... – Duncan Armstrong Mar 13 '14 at 10:00

10 Answers10

141

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.

falsarella
  • 12,217
  • 9
  • 69
  • 115
Adrian Mitev
  • 4,722
  • 3
  • 31
  • 53
  • 4
    @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`. – Drew Dormann Jan 17 '12 at 19:57
  • 3
    Opening up this Pandora's box - where do you see that "IEEE demands that (NAN != NAN) == false"? – Supervisor Jan 26 '16 at 21:30
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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Is it implemented by the CPU, or is it hard-wired in the JVM as Bohemian mentions? – Naweed Chougle Jan 11 '12 at 16:56
  • 3
    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) – Peter Lawrey Jan 11 '12 at 17:05
  • 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. – user207421 Mar 26 '15 at 18:14
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);
falsarella
  • 12,217
  • 9
  • 69
  • 115
  • 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. – supercat Sep 07 '13 at 20:33
  • @supercat 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. [http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#equals(java.lang.Object)] – falsarella Sep 09 '13 at 11:52
  • @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. – supercat Sep 11 '13 at 16:36
  • @supercat 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. – falsarella Sep 11 '13 at 17:22
  • 1
    @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. – supercat Sep 11 '13 at 18:08
  • @supercat 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 equal – GoogieK Mar 17 '14 at 00:39
  • @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. – supercat Mar 27 '15 at 00:42
  • @supercat 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. – falsarella Mar 27 '15 at 00:43
  • @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. – supercat Mar 27 '15 at 15:03
  • @supercat I agree: it's faster. I just wanted to add that the behaviors are different. – falsarella Mar 28 '15 at 00:36
  • 1
    best and simple answer. Thank you – Tarun Nagpal Jul 05 '16 at 15:58
  • `Double.NaN.equals/compareTo` is not valid code! `Double.NaN` is a `double` and you can't invoke method on it. – user1803551 Jan 04 '18 at 18:39
  • `Double.NaN.equals(Double.NaN)`: Did you mean `Double.valueOf(...).equals(Double.valueOf(...))` ? – antak Aug 05 '20 at 02:13
  • That's the way. The Double instance equality will consider NaNs as equal. – falsarella Aug 05 '20 at 02:18
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

JREN
  • 3,572
  • 3
  • 27
  • 45
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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
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"
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
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

Matteo
  • 1,367
  • 7
  • 25
  • -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 @AdrianMitev – ANeves Jan 11 '12 at 19:02
  • 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 (http://en.wikipedia.org/wiki/NaN). – Matteo Jan 12 '12 at 12:03
  • Also, this is in the Java source for Double: public static final double NaN = 0.0d / 0.0; – Guillaume Jan 12 '12 at 12:13
  • 1
    @Matteo +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. – ANeves Jan 12 '12 at 14:58
  • @Guillaume if that comment was meant for me, please rephrase it: I do not understand it. – ANeves Jan 12 '12 at 14:59
  • @ANeves 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. – Matteo Jan 12 '12 at 15:52
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".

Tiina
  • 4,285
  • 7
  • 44
  • 73
0

if you have variable

Double a = Double.NaN

use

String.valueOf(Double.NaN) == a.toString()
Eliko
  • 61
  • 1
  • 2