This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Robert.Withrow
Recipients Robert.Withrow, TD22057, loewis, mark.dickinson, rhettinger, vstinner
Date 2011-03-18.19:07:54
SpamBayes Score 1.2490009e-14
Marked as misclassified No
Message-id <1300475276.22.0.935135731589.issue4114@psf.upfronthosting.co.za>
In-reply-to
Content
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...  ;-)
History
Date User Action Args
2011-03-18 19:07:56Robert.Withrowsetrecipients: + Robert.Withrow, loewis, rhettinger, mark.dickinson, vstinner, TD22057
2011-03-18 19:07:56Robert.Withrowsetmessageid: <1300475276.22.0.935135731589.issue4114@psf.upfronthosting.co.za>
2011-03-18 19:07:54Robert.Withrowlinkissue4114 messages
2011-03-18 19:07:54Robert.Withrowcreate