NaN comparisons - Call For Anecdotes

Ian Kelly ian.g.kelly at
Tue Jul 8 17:23:47 CEST 2014

On Tue, Jul 8, 2014 at 8:53 AM, Anders J. Munch <2014 at> wrote:
> And that worked fine in my Python 2.4 apps.  Then I upgraded to 2.7
> and it broke.  Because 2.7 goes out of it's way to ensure that NaN's
> don't compare equal to themselves.

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

> I discovered it when a sanity check told me that two functions,
> to_binary and from_binary, weren't each other's inverse, as they were
> intended to be.  Apparently,
> bitPattern==to_binary(from_binary(bitPattern)) wasn't true for this
> particular value of bitPattern.  Of course, the bit pattern in
> question was the binary representation for a floating-point NaN.

Okay, here's your problem: there isn't just one binary representation
for NaN.  The standard defines any value with all 1's in the exponent
and a non-zero significand as NaN (a zero significand would instead be
an infinity).  Your bit comparison is going to have to be prepared to
compare NaNs that don't have the same binary representation.

By the way, there are also multiple binary representations for 0.  If
you compare them as floats, then they'll compare equal to one another,
but if you're just comparing binary representations then you'll have
issues there as well.

> Now, all this bothers me.  Not that I had to do some work to get stuff
> to work in an imperfect world.  No, what bothers me is that this
> behaviour was explicitly and deliberately put in for no good reason.
> The only reason is "standard says so". Not that there's any legal
> requirement for Python to follow the IEEE-754 standard. Or for that
> matter, for Python's spelling of IEEE-754 comparisons to be "==".

Following the standard isn't a good reason itself?  It seems to me
that one should be expected to provide a strong justification for
*deviating* from the standard, not for following it.

More information about the Python-list mailing list