Search code examples
javafloating-pointieee-754

Why does comparison of NAN return true?


As written in Java Language Specification 'The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN' So I was comparing two NAN's. Why does it print true in the console when I compare two NAN?

double f = 3/0.0d;
double h = 2/0.0d;
        
System.out.println((f>=h));

f and h are both NAN and when i compared them i expected to print false but i got true as my output.


Solution

  • 2.0/0 doesn't produce NaN:

    System.out.println(2.0/0.0);
    > Infinity
    

    There are 3 'non-numeric' values of doubles:

    • Positive infinity
    • Negative infinity
    • NaN

    As per spec, positiveinfinity is equal to positive infinity, and negative infinity is equal to negative infinity. Only NaN isn't equal to itself.

    we can get NaN:

    double nan = 0.0 / 0.0;
    System.out.println(nan);
    System.out.println(nan == nan);
    > NaN
    > false
    

    If you actually need NaN somewhere (e.g. you want to return it), the most legible way to get there is Double.NaN. The above example simply shows how one might get a NaN value out of a calculation naturally - when zero is divided by zero is the most common way. A few other ways:

    double posInf = Double.POSITIVE_INFINITY;
    double negInf = Double.NEGATIVE_INFINITY;
    System.out.println(posInf - posInf); // NaN
    System.out.println(posInf - negInf); // positive infinity
    System.out.println(posInf / posInf); // NaN