Portably generating infinity and NaN
Duncan Booth
duncan.booth at invalid.invalid
Sat Apr 14 07:47:32 EDT 2007
skip at pobox.com wrote:
> % 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?
How about doing the same in reverse to generate the values on Windows? It
should be pretty portable, otherwise the struct module doesn't work as
advertised:
>>> NaN, Inf = struct.unpack("!2f", '\x7f\xc0\x00\x00\x7f\x80\x00\x00')
>>> NaN,Inf
(1.#QNAN, 1.#INF)
This also means you can choose which NaN you generate, although given
that it compares unequal with itself it probably doesn't matter.
More information about the Python-list
mailing list