Question

I have the code below:

sim = top / bottom;

if(sim == Double.NaN) {
    System.out.println("sim is NaN");
} else {
    System.out.println(sim);
}

For some values in my program, top / bottom is 0.0 / 0.0 which should be equal to Double.NaN but when I stop at a breakpoint after this section the output shows 'NaN' -i.e. the value of sim rather than 'Sim is NaN'.

Why does my test for sim == Double.NaN return false if I see it as 'NaN' in the debugger?

Was it helpful?

Solution

You can check for NaN only via Double.isNan():

if (Double.isNaN(sim)) {
  // is Nan
} else {
  // not nan
}

On first thoughts that is not intiutive, you have to know it. The reason behind it, is that this is specified by IEEE Floating Point standard.

You can argument: NaN is not a number, it can be anything but not a number, so two NaN cannot be compared to be equal.
For example = 0.0 / 0.0 is NaN; and sqrt(-1) is NaN, too. But that values cannot be compared to be the same.

Additional reading: http://en.wikipedia.org/wiki/NaN

OTHER TIPS

That's because nothing is equal to NaN, not even NaN itself. This is specified in the JLS, Section 15.21.1:

  • If either operand is NaN, then the result of == is false but the result of != is true.

Indeed, the test x!=x is true if and only if the value of x is NaN.

The methods Float.isNaN and Double.isNaN may also be used to test whether a value is NaN.

To test for NaN, you must Double's isNaN method.

if (Double.isNaN(sim)) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top