[issue4114] struct returns incorrect 4 byte float

Robert Withrow report at bugs.python.org
Thu Mar 17 18:55:12 CET 2011


Robert Withrow <bigbaaadbob at gmail.com> added the comment:

> If you agree that Python actually behaves correct, I fail to
> understand what it is that you disagree with in msg131195

I don't agree that Python is behaving correctly as far as the documented contract for struct is concerned.

I disagree with the statement in the preceding msg74708 which says:

> people should read general CS introductory material
> to learn how floating point numbers work.

Aside from being patronizing it doesn't solve the problem in any meaningful way.

> If you use numbers that are exactly representable as floats,
> the test should be portable to all platforms that use 32-bit
> IEEE-754 floats.

A reasonable suggestion, but it is a constrained definition of "portable".  Since most (or nearly all?) modern platforms use '754 it is probably not a bad constraint, given that struct explicitly uses '754.

> If you then also use numbers without a fractional
> part, it should even port to non-IEEE platforms

I confess, the "CS introductory material" I read 30 years ago (predating '754) don't give me enough information to know if this is correct.

Anyway:

> If all you want is a documentation change, can you please propose
> specific wording?

It isn't exactly "all I want", but it is a good start.  I note that msg74705 suggests adding documentation to struct about the 'f' format code.

First of all, as far as I know, struct is the only place where this issue of 32 bit versus 64 bit floating point numbers shows up in Python because the rest of Python uses only 64 bit numbers.  (Is there anywhere else in Python where a 32 bit float is converted to a 64 bit float?) So the documentation probably belongs in struct.

I would add to note 4 of 7.3.2.2 (in the 2.7.1 documentation) something like:

"Note that 32 bit representations do not generally convert exactly to 64 bit representations (which Python uses internally) so that the results of unpack(fmt,pack(fmt,number)) may not equal number when using the 'f' format character."

It would be friendly to add an example at the bottom demonstrating the issue and incorporating your comments about fractions and non-fractional values.

>>> x = unpack('!f', pack('!f', 6.24))[0]
>>> x == 6.24
False
>>> x = unpack('!f', pack('!f', 6.25))[0]
>>> x == 6.25
True

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue4114>
_______________________________________


More information about the Python-bugs-list mailing list