[Python-ideas] checking for identity before comparing built-in objects

Alexander Belopolsky alexander.belopolsky at gmail.com
Mon Oct 8 05:46:43 CEST 2012

On Sun, Oct 7, 2012 at 11:09 PM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> Couldn't each NAN when generated contain something that identified it
> uniquely, so that different NANs would always compare as not equal, but any
> given NAN would compare equal to itself?

If we take this route and try to distinguish NaNs with different
payload, I am sure you will want to distinguish between -0.0 and 0.0
as well.  The later would violate transitivity in -0.0 == 0 == 0.0.

The only sensible thing to do with NaNs is either to treat them all
equal (the Eiffel way) or to stick to IEEE default.

I don't think NaN behavior in Python is a result of a deliberate
decision to implement IEEE 754.  If that was the case, why 0.0/0.0
does not produce NaN?  Similarly, Python math library does not produce
infinities where IEEE 754 compliant library should:

>>> math.log(0.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Some other operations behave inconsistently:

>>> 2 * 10.**308

>>> 10.**309
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')

I think non-reflexivity of nan in Python is an accidental feature.
Python's float type was not designed with NaN in mind and until
recently, it was relatively difficult to create a nan in pure python.

It is also not true that IEEE 754 requires that nan == nan is false.
IEEE 754 does not define operator '==' (nor does it define boolean
false).  Instead, IEEE defines a comparison operation that can have
one of four results: >, <, =, or unordered.  The standard does require
than NaN compares unordered with anything including itself, but it
does not follow that a language that defines an == operator with
boolean results must define it so that nan == nan is false.

More information about the Python-ideas mailing list