Portably generating infinity and NaN

Robert Kern robert.kern at gmail.com
Thu Apr 12 21:53:16 CEST 2007

Michael Hoffman wrote:
> What's the best way to portably generate binary floating point infinity 
> and NaNs? I only know two solutions:
> 1. Using the fpconst module proposed in IEEE 754, which I believe shifts 
> bits around.
> 2. Using an extension module (for example, numarray.ieeespecial will do it).
> I thought of using float(Decimal("nan")), but apparently 
> Decimal.__float__(self) is float(str(self)), which isn't portable.

This is what numpy does (translated from the C):

mul = 1e10
inf = mul
tmp = 0.0
while True:
    inf *= mul
    if inf == tmp:
    tmp = inf

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