Bug in floating point multiplication

Jason Swails jason.swails at gmail.com
Thu Jul 2 19:29:35 CEST 2015


On Thu, Jul 2, 2015 at 10:52 AM, Steven D'Aprano <steve at pearwood.info>
wrote:

> 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.
>

​
As others have suggested, this is almost certainly a 32-bit vs. 64-bit
issue.  Consider the following C program:

// maths.h
#include <math.h>
#include <stdio.h>

int main() {
    double x;
    int i;
    x = 1-pow(0.5, 53);

    for (i = 1; i < 1000000; i++) {
        if ((int)(i*x) == i) {
            printf("%d\n", i);
            break;
        }
    }

    return 0;
}

For the most part, this should be as close to an exact transliteration of
your Python code as possible.

Here's what I get when I try compiling and running it on my 64-bit (Gentoo)
Linux machine with 32-bit compatible libs:

swails at batman ~/test $ gcc maths.c
swails at batman ~/test $ ./a.out
swails at batman ~/test $ gcc -m32 maths.c
swails at batman ~/test $ ./a.out
2049

That this happens at the C level in 32-bit mode is highly suggestive, I
think, since I believe these are the actual machine ops that CPython float
maths execute under the hood.

All the best,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150702/fd3a0ba0/attachment.html>


More information about the Python-list mailing list