Portably generating infinity and NaN

skip at pobox.com skip at pobox.com
Sat Apr 14 00:18:54 CEST 2007


    Michael> What's the best way to portably generate binary floating point
    Michael> infinity and NaNs? 

I take it this isn't portable even though it works on Mac, Linux and Solaris
across a number of different Python versions and a couple GCC versions:

    % python
    Python 2.4.2 (#1, Feb 23 2006, 12:48:31) 
    [GCC 3.4.1] on sunos5
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import struct
    >>> struct.pack("f", float("NaN"))
    '\xff\xff\xff\x7f'
    >>> struct.pack("f", float("Inf"))
    '\x00\x00\x80\x7f'

    $ python
    Python 2.5 (release25-maint:53536, Jan 23 2007, 18:15:37) 
    [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import struct
    >>> struct.pack("f", float("NaN"))
    '\x00\x00\xc0\x7f'
    >>> struct.pack("f", float("Inf"))
    '\x00\x00\x80\x7f'

    % python
    Python 2.6a0 (trunk:54264M, Mar 10 2007, 15:19:48) 
    [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import struct
    >>> struct.pack("f", float("Inf"))
    '\x7f\x80\x00\x00'
    >>> struct.pack("f", float("NaN"))
    '\x7f\xc0\x00\x00'

(Note the absence of a demonstration on Windows.)  Can't the above be
blessed as the One True Way and wormed around in floatmodule.c for those
platforms where float'ing "NaN" or "Inf" doesn't currently work?

Skip



More information about the Python-list mailing list