struct doesn't handle NaN values?

Tim Peters tim.one at comcast.net
Thu May 13 16:09:10 EDT 2004


[Grant Edwards]
> Perhaps I'm doing something wrong:

Not really.

> the struct module docs say it's IEE 754, but I can't figure out
> how to get it to handle NaN values correctly (either packing or
> unpacking).

All Python behavior in the presence of 754 special values (infs, NaNs,
signed zeroes) is a platform-dependent accident.  There's a growing list of
these in PEP 42 (under "Non-accidental IEEE-754 support"), but nobody even
bothers to keep that up to date.

> >>> x = float('nan')

It's even an accident that this line didn't raise an exception (it does, for
example, under the Windows Python).

> >>> struct.pack("<f",x)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> SystemError: frexp() result out of range

An accident of what your platform C's frexp() happens to do with a NaN.

> >>> struct.unpack("<f",'\xff\xff\xff\xff') (-6.8056469327705772e+38,)

The C routine that gets invoked here is _PyFloat_Unpack4(), in
floatobject.c.  As the comment there says,

	/* XXX This sadly ignores Inf/NaN issues */

That is, the outcome of this is also an accident.





More information about the Python-list mailing list