[Python-ideas] Why is nan != nan?

Adam Olsen rhamph at gmail.com
Fri Mar 26 03:26:28 CET 2010

On Thu, Mar 25, 2010 at 20:01, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> So we have three correctness-preserving possibilites:
> 1) Always raise an exception as soon as a NaN is
>   produced.
> 2) Propagate NaNs through arithmetic but raise an
>   exception when attempting to compare them.

This forces you to explicitly compare them when desired, but it's even
simpler than I realized (and doesn't require new functions).

def func(a, b):
   if not isnan(a) and not isnan(b) and a == b:
       return 1.0
   return math.sin(a*b)**(a-b)

All it requires is you check for NaN before your normal comparison.
It's even backwards compatible with Python 2.6!

If that example is a little verbose for you, just make isnan take
multiple arguments and return true if any are NaN.

> 3) Return a NaB when comparing NaNs, and raise an
>   exception when attempting to branch on a NaB.

Adam Olsen, aka Rhamphoryncus

More information about the Python-ideas mailing list