Vishrant
Vishrant

Reputation: 16628

Float and Double NaN (Not-a-Number) value

I was reading JLS8 4.2.3 there I found concept for Float NaN and Double NaN. When I opened the source code of Float and Double class, and tried following code:

1st condition:
if (Float.NaN == Float.intBitsToFloat(0x7fc00000)) 
    System.out.println("Both are equal");
}

2nd condition:
if (Float.NaN == (0.0f / 0.0)) {
    System.out.println("Equal");
}

According to documentation: An NaN is

/**
 * A constant holding a Not-a-Number (NaN) value of type
 * {@code float}.  It is equivalent to the value returned by
 * {@code Float.intBitsToFloat(0x7fc00000)}.
 */

Then why my both conditions are false. And in eclipse for 2nd condition I was getting warning: Dead Code.

Same thing with Double NaN.

Upvotes: 1

Views: 1137

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

Because floating-point defines NaN == NaN to be false. (This makes sense; 0/0 and acos(2) are both NaN, but that doesn't mean that they're equal to each other in any useful sense.)

Use Float.isNaN() to determine whether something is NaN.

Upvotes: 2

fge
fge

Reputation: 121702

As a complement to other answers, you can test whether a float is NaN using either of:

Float.isNaN(myFloat);

or:

Float.compare(Float.NaN, myFloat) == 0

The same is true for Double.NaN; and the Double class has a similar method.

Upvotes: 2

Ingo
Ingo

Reputation: 36329

This is because NaN is, by definition, not equal to anything. It is used to model a something, and all we know about this something is that it is not a number.

Think of it like this: A chair is NaN, your screen is also NaN (not a number), yet, your chair is not the same as your screen.

Likewise, given that Jane is not your mother and John is not your mother, it makes no sense to insist that Jane and John must be the same person.

Upvotes: 3

Related Questions