Robert Withrow <[email protected]> added the comment:
For completeness: msg131234 states that the issue of 64 bit -> 32 bit precision
truncation is covered in the floating point tutorial. I believe that is
incorrect; at least I can't find it explicitly mentioned. Ref:
http://docs.python.org/tutorial/floatingpoint.html.
If struct is the only place this (64->32 bit precision truncation) can happen
in Python, the lack of discussion in the tutorial makes sense. Otherwise, a
sentence about it should be added to the tutorial.
As it is, there is no _explicit_ mention of this anywhere in Python
documentation. It is all well and good to state that it is "obvious", but it
seems that explicit documentation is preferable to implicit documentation,
given the rarity of the issue in Python and the meager cost of adding a
sentence here or there.
Incidentally, it is simple to create the truncation routine I mention earlier:
>>> def fptrunc(value):
... return unpack('!f', pack('!f', value))[0]
...
>>> fptrunc(6.24)
6.2399997711181641
>>> fptrunc(6.25)
6.25
But this has the questionable smell of using pack/unpack in a test of
pack/unpack. It's sorta OK for _users_ of pack/unpack though.
A quick scan of the Python source code shows that only two things try to pack 4
byte floats: struct and ctypes and both of these use the underlying Python
float object routines. So a better way of doing the truncation is to use
ctypes:
>>> def fptrunc(value):
... return c_float(value).value
...
>>> fptrunc(6.24)
6.2399997711181641
>>> fptrunc(6.25)
6.25
Doing this allows you to write tests that work for any number and don't require
the use of magic numbers or knowledge of the underlying floating point
implementation.
Even if nothing gets put into the documentation, people will probably find this
discussion by Googling.
I can't imagine there is much more that can be said about this, so I'll leave
you guys alone now... ;-)
----------
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue4114>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com