NaN comparisons - Call For Anecdotes

Ian Kelly ian.g.kelly at
Tue Jul 8 21:57:30 CEST 2014

On Tue, Jul 8, 2014 at 12:54 PM, Anders J. Munch <2014 at> wrote:
> Ian Kelly wrote:
>> As far as I know nothing changed between 2.4 and 2.7 in this regard.
>> Python has always had NaN compare unequal to everything, per the
>> standard.
> It might have been platform-specific in 2.4.

I doubt it, but okay, which platform?

>> Okay, here's your problem: there isn't just one binary representation
>> for NaN.
> I'm fully aware of that. Whether NaN's are one equivalence class or several
> is not the issue. What matters is the integrity of the equivalence relation.

I have some bad news for you.  This is on Python 2.7.6:

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Decimal(2) == 2
>>> 2 == Fraction(2)
>>> Decimal(2) == Fraction(2)

I'm not sure exactly when this bug was fixed, but it works as expected in 3.4.0.

>> Following the standard isn't a good reason itself?
> If a standard tells you to jump of a cliff...

So I don't know of a good use case for nan != nan in Python (but
really I'm not the one to ask), but I do know of use cases in other
scenarios.  On platforms that don't provide an isnan() function, the
only convenient and efficient way to test for nan is by testing
reflexivity: x != x.

Following the standard means that any algorithm that uses this trick
can (in theory) be implemented in Python without changes.

More information about the Python-list mailing list