Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NaN Constant Magic in Java [duplicate]

Tags:

java

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

NaN = "NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.

I was trying to use NaN Constant in Java

public class NaNDemo {
    public static void main(String s[]) {
        double x = Double.NaN;
        double y = Double.NaN;

        System.out.println((x == y));
        System.out.println("x=" + x);
        System.out.println("y=" + y);
    }
}

Output

false
x=NaN
y=NaN

So why x==y is false ?

like image 922
Rahul Agrawal Avatar asked Oct 06 '22 12:10

Rahul Agrawal


1 Answers

NaN is a concept, not a value or a number. Since that concept can represent multiple non-real-number values (imaginary, 0/0, etc) it doesn't make sense to say that any particular NaN is equal to any other NaN.

Similarly you can't say that Double::NEGATIVE_INFINITY equals itself, since infinity is not a number either.

like image 128
maerics Avatar answered Oct 10 '22 03:10

maerics