Search code examples
pythonequality

Comparing "float('nan')" and "math.nan"


I have a float variable which may or may not be a number, and I want to check if that is the case. With x = float('nan'), I observed some behavior that surprised me:

    print(x is math.nan)
>>> False

This means that float('nan') and math.nan are different objects, which I didn't expect, but that's okay. However, the result is the same, when I check for equality with ==:

print(x == math.nan):
>>> False

I get the correct result for all kinds of not-a-number, if I use math.isnan(x). Still, why doesn't float('nan') == math.nan evaluate to True?.


Solution

  • "Not a number" is (in some sense) the absence of a value.

    Traditionally, and per the IEEE floating-point specification, it does not equal itself.

    That's because there is no meaningful value to compare.

    In fact, some people use this fact to detect NaN, so you could try x != x as your condition instead (though the linked Q&A arguably has some better suggestions).

    The expression math.nan is math.nan is true, though, because is does an object identity comparison rather than a value equivalence/equality comparison.