0

Possible Duplicate:
Why does Double.NaN==Double.NaN return false?

This is purely out of curiosity.

I did something like this:

public static void main(String args[]) throws Exception {
        System.out.println(Double.NaN==Double.NaN);
    }

The output is false. Shouldn't this return true?

Why is it so?

Community
  • 1
  • 1
Avinash Nair
  • 1,984
  • 2
  • 13
  • 17

2 Answers2

5

From the Java Language Specifications:

Floating-point operators produce no exceptions (§11). 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.

The important sentence here is:

so a numeric comparison operation involving one or two NaNs returns false

RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
  • and for not comparing floating point numbers for equality see http://stackoverflow.com/questions/3832592/test-for-floating-point-equality-fe-floating-point-equality – palindrom Jan 30 '13 at 12:55
  • Good explanation. To explain it further, NaN basically mean that this number does not exist (Not a Number). Something that does not exist is equal to nothing. In maths, for example, you DO NOT have 3/0 = 4/0 (this is Nan = Nan, basically). This does not make any sense. – autra Jan 30 '13 at 12:55
0

For comparing two Doubles better use the #compareTo(Double) method, it is able to handle NaN and XXX_INFINITY in a separated way.

Compares two Double objects numerically. There are two ways in which comparisons performed by this method differ from those performed by the Java language numerical comparison operators (<, <=, ==, >=, >) when applied to primitive double values:

Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY). 0.0d is considered by this method to be greater than -0.0d. This ensures that the natural ordering of Double objects imposed by this method is consistent with equals.

public static void main(String[] args) {
  Double d = new Double(Double.NaN);
  System.out.println(d.compareTo(Double.NaN) == 0);//returns true
}
Simulant
  • 19,190
  • 8
  • 63
  • 98