python 3.44 float addition bug?

Chris Angelico rosuav at gmail.com
Fri Jun 20 21:33:25 EDT 2014


On Sat, Jun 21, 2014 at 10:57 AM, FraserL
<fraser.long+usenet at nospamgmail.com> wrote:
> #test code
> z = 0.01
> p = 0.0
> for x, y in enumerate(range(1, 20)):
>     p += z
>     print(p)
> #end

General tip when you think you've found a bug: Cut out everything that
isn't part of it. In this case, the enumerate has nothing to do with
what you're seeing, which is an artifact of floating-point arithmetic,
so a more classic loop header would simply be:

for i in range(19):

(Or some people will use _ to emphasize that the iterated-over values
are being ignored.)

The smaller you can make your test code, the more likely that people
will be able to see what's going on.

Also, when you're looking at how things print out, consider looking at
two things: the str() and the repr(). Sometimes just "print(p)"
doesn't give you all the info, so you might instead want to write your
loop thus:

z = 0.01
p = 0.0
for i in range(19):
    p += z
    print(str(p) + " -- " + repr(p))

Sometimes you can get extra clues that way, although in this instance
I think you won't.

ChrisA



More information about the Python-list mailing list