[issue25129] suboptimal floating-point floor division

Tim Peters report at bugs.python.org
Tue Sep 15 21:24:37 CEST 2015


Tim Peters added the comment:

Stare at footnote 2 for the Reference Manual's "Binary arithmetic operations" section:

"""
[2] If x is very close to an exact integer multiple of y, it’s possible for x//y to be one larger than (x-x%y)//y due to rounding. In such cases, Python returns the latter result, in order to preserve that divmod(x,y)[0] * y + x % y be very close to x.
"""

This is such a case.

>>> x
4.679999999999999e-06
>>> y
6e-08
>>> divmod(x,y)[0] * y + x % y == x
True
>>> (x/y) * y + x % y == x
False
>>> ((x/y) * y + x % y) / x # and not close at all
1.0128205128205128

Yes, trying to preserve identities in floating-point always was a fool's errand ;-)

Note that "but x is an _exact_ integer multiple of y, not just 'very close to'" would be succumbing to an illusion:

>>> dx = decimal.Decimal(x)
>>> dy = decimal.Decimal(y)
>>> dx / dy
Decimal('77.99999999999999426488108630')

It's just that x/y _appears_ to be an exact integer (78) due to rounding.  As the decimal calcs show, infinite-precision floor division really would return 77.

----------

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


More information about the Python-bugs-list mailing list