Possible Duplicate:
Python rounding error with float numbers
I have a rounding Problem in Python. If i calculate
32.50 * 0.19 = 6.1749999999999998
But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.
But if i calculate this:
32.50 * 0.19 * 3 = 18.524999999999999
This should be 18.525. If i round the value 18.524999999999999 with two decimal places it shows 18.52.
It should show me 18.53. What am i doing wrong and how can i fix it ?
If you need exact arithmetic, you could use the decimal module:
You are not doing anything wrong. This is due to the internal representation of the numbers:
For example, try this:
If you need more precision use the decimal representation
You're doing nothing wrong, and it isn't Python's fault either. Some decimal numbers just cannot be precisely represented as binary floats.
Just like you can't write
1/3
in decimal (0.33333....
), you can't write decimal0.1
in binary (0.0001100110011001100110011001100110011001100110011...
).Solution A:
Use
print 32.5 * 0.19
- it will automatically round the result.Solution B:
Use the
Decimal
module if you actually need this precision, for example when calculating with monetary values.Solution C:
Use Python 3.2 or Python 2.7 which will automatically round the result in an interactive session.
I don't think that is wrong. Take this from the Python interpreter:
In both cases, the number being rounded was less than 5, so it rounded down. 18.52, and 6.17.
That is correct.
One thing I don't get is why you are getting 6.18, and I get 6.17. I am using Python 3.2.2 (the latest version)
http://docs.python.org/library/functions.html#round
What Every Computer Scientist Should Know About Floating-Point Arithmetic.
In short - you should not rely on precise values of float numbers because of the way they are stored in the memory.
See also python docs about it - Floating Point Arithmetic: Issues and Limitations. It contains the next passage: