Floats and NaNs

Robert Kern robert.kern at gmail.com
Mon Dec 3 12:36:42 EST 2007


Dalton, Tom wrote:
> Hi,
> 
> Is there any way to detect if a float is NaN in Python 2.4?
> 
> I can pretty much understand why
> 
> float("nan") == float("nan") -> False
> 
> but I then expected there to be an isnan() function, perhaps provided by
> the maths module. I understand a lot of the floating point behaviour is
> implementation-dependant, but for systems where special values such as
> nan, inf etc are supported, it would be nice (IMHO) for Python to
> support them to some degree too. Is this possible or does it get too
> bogged down with implementation specifics? A <nasty> solution I guess
> would be to do something like
> 
> my_float = float("nan")
> If str(my_float) == "nan":
>     doSomething()
> 
> But that's awful!
> 
> Any help or reasons why the functionality isn't provided would be
> gratefully received!

Python does not require IEEE-754 floats, and NaNs and infs are IEEE-754 features.

A simple (and probably reasonably robust) implementation of isnan() in Python:

  def isnan(x):
    return isinstance(x, float) and (x != x)

BTW, you cannot reliably construct NaNs with float('nan'). That only works on
some systems (usually UNIXy ones). Windows does not support that. The best way
I've found to construct NaNs and infs follows:

  inf = 1e200 * 1e200
  nan = inf / inf

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco




More information about the Python-list mailing list