Bug in floating point multiplication

Peter Otten __peter__ at web.de
Sun Jul 5 03:38:24 EDT 2015


Laura Creighton wrote:

> In a message of Fri, 03 Jul 2015 00:52:55 +1000, "Steven D'Aprano" writes:
>>Despite the title, this is not one of the usual "Why can't Python do
>>maths?" "bug" reports.
>>
>>Can anyone reproduce this behaviour? If so, please reply with the version
>>of Python and your operating system. Printing sys.version will probably
>>do.
>>
>>
>>x = 1 - 1/2**53
>>assert x == 0.9999999999999999
>>for i in range(1, 1000000):
>>    if int(i*x) == i:
>>        print(i); break
>>
>>
>>Using Jython and IronPython, the loop runs to completion. That is the
>>correct behaviour, or so I am lead to believe. Using Python 2.6, 2.7 and
>>3.3 on Centos and Debian, it prints 2049 and breaks. That should not
>>happen. If you can reproduce that (for any value of i, not necessarily
>>2049), please reply.
>>
>>See also http://bugs.python.org/issue24546 for more details.
>>
>>
>>
>>--
>>Steven
> 
> PyPy says:
> Python 2.7.9 (2.5.1+dfsg-1, Mar 27 2015, 19:45:43)
> [PyPy 2.5.1 with GCC 4.9.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>>> x = 1 - 1/2**53
>>>>> assert x == 0.9999999999999999
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AssertionError
>>>>> for i in range(1, 1000000):
> ....     if int(i*x) == i:
> ....             print(i); break
> ....
> ....
> 1
>>>>> 
> 
> So the loop terminates, but there is an Assertion Error.  Did you want
> that?

No. Steven's environment implies

from __future__ import division

which he forgot to mention in the original post:

>>>> x = 1-1/2**53
>>>> x
1
>>>> from __future__ import division
>>>> x = 1-1/2**53
>>>> x
0.9999999999999999






More information about the Python-list mailing list