I had some problems with some Python projects that gave variable
results that I could not track down. Eventually and reluctantly I
converted them to Java. Later, when I had more time I tried to analyze
what the Python code was doing and found something strange. The
following snippet illustrates the problem.

>>> i = -50.0
>>> for x in xrange(5):
        i += 0.1
        z = i * 10.0
        print
        print z
        print int(z)

-499.0
-499

-498.0
-498

-497.0
-496

-496.0
-495

-495.0
-494


The first two iterations look OK but after that the int(z) function
returns the wrong value. It looks like the value was rounded down.  If
a just do this:
>>> int(-497.0)
-497
I get the value I expect.
So what is the problem?

It looks like a rounding problem but on the surface there is nothing
to round. I am aware that there are rounding limitations with floating
point arithmetic but the value passed to int() is always correct. What
would cause it to be off by 1 full digit in only some cases? Perhaps
something behind the scenes in the bowels of the interpreter ?.

I could not get the thing to fail without being inside the for loop;
does that have something to do with it?

To fix the problem I could use round() or math.floor().  Like this.

>>> i = -50.0
>>> for x in xrange(5):
        i += 0.1
        z = i * 10.0
        print
        print z
        print(round(z))

-499.0
-499.0

-498.0
-498.0

-497.0
-497.0

-496.0
-496.0

-495.0
-495.0

Why should I have to do this?

Is there a general rule of thumb to know when this could be a problem?

Should any float-to-int conversion be suspect?

The above code was run in Python 2.5.4 on WinXP and Python 2.6.2 on
Linux(Fedora12)
Can anyone verify if this would be the same on 3.x?
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to