Why is double.NaN not equal to itself?

Viewed 25140

Can someone explain this to me? In C# double.NaN is not equal to double.NaN

bool huh = double.NaN == double.NaN; // huh = false
bool huh2 = double.NaN >= 0; // huh2 = false
bool huh3 = double.NaN <= 0; // huh3 = false

What constant can I compare to a double.NaN and get true?

11 Answers

If you are curious, this is what Double.IsNaN looks like:

public static bool IsNaN(double d)
{
    return (d != d);
}

Funky, huh?

bool isNaN = Double.IsNaN(yourNumber)

The behavior is on purpose. The reason being NaN represents something that is not a number and so that is sort of a catch-all for many things.

The proper way to compare something to being NaN is to use the IsNaN function.

Use Double.IsNan() to test for equality here. The reason is that NaN is not a number.

There's a specialized function for this:

double.IsNan(huh);

Use the method "Double.IsNaN( value )" to check for this condition.

Actually, you already found the way to check if a IEEE-754 floating point number is NaN: it is the only floating point value (or range of values, because there are several NaNs) that evaluates to False if compared to itself, i.e. :

bool isNaN(double v) {
    return v != v;
}

Under the hood, the Double.IsNaN method might actually do the same thing. You should still use it, because the behavior is quite surprising to anybody who does not know about the FP standard.

The only thing that we know about NaN is that it's "Not a Number." That doesn't mean that it has a value that is associable with its state. For example:

∞ + (-∞) = NaN

0/0 = NaN

(∞ + (-∞)) <> (0/0)

Here's some C# to demonstrate

var infinity = 100d / 0;
var negInfinity = -100d / 0;

var notANumber = infinity + negInfinity;
Console.WriteLine("Negative Infinity plus Infinity is NaN: {0}", double.IsNaN(notANumber));

var notANumber2 = 0d / 0d;
Console.WriteLine("Zero divided by Zero is NaN: {0}", double.IsNaN(notANumber2));

Console.WriteLine("These two are not equal: {0}", notANumber == notANumber2);
Related