test for nan

David M. Cooke cookedm+news at physics.mcmaster.ca
Tue Mar 30 17:43:21 EST 2004


At some point, John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote:

> I have a C extension module that is returning some doubles.  When the
> doubles get out of range, the numbers print as 'nan'.
>
> Is there a better way to test for NaN than
>
>    str(p1)=='nan'
>
> where p1 is a float?

The string representation of NaN is system-dependent. On Windows it's
something like #NaN. You'd be better off with Jeff Epler's suggestion
of wrapping isnan() (since you already have a C extension module, you
could through it in there).

If you're on something that uses IEEE floating-point representations,
something like this in pure python should work:

import struct
def isnan(x):
    s = struct.pack('d', x)
    if struct.pack('h', 1) == '\x01\x00':
        return s == '\x00\x00\x00\x00\x00\x00\xf0\x7f':
    else:
        return s == '\x7f\xf8\x00\x00\x00\x00\x00\x00':

The test for endianness is there since struct.unpack('<d', x)
complains that frexp() is out of range.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list