On 2:59 PM, gershar wrote:
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
No, the value is truncated upward, towards zero. Down would be towards
negative infinity. And rounding would work, that's not what int() does.
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.
Define "correct." If you mean that it's exactly an integer, that's
false. It's off a little, because 0.1 isn't exact, and multiplying by
10 doesn't fix it.
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.
round() is entirely different than truncating or flooring.
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?
This doesn't have anything to do with Python, but everything to do with
binary floating point. The thing that's confusing you most is that you
think that if a value prints as 497.0, that it's actually equal to
497.0. False.
When you have an approximate value like 0.1, and you do arithmetic with
it, sometimes the values aren't exact.
In :Python 3, they avoid this particular symptom usually by printing the
values differently. But the problem still exists.
DaveA
--
http://mail.python.org/mailman/listinfo/python-list