this is my first time asking on stackoverflow, and I have a trouble when programming with python 2.7.
Here I have a calculation:
1350/2.7
The exact answer must be 500, but python give the answer 499.99999999999994
I know about the fact that some numbers cannot be represented exactly in binary, causing error on floating calculation.
So can anybody give me an advice? How to deal exactly with it?
Asked
Active
Viewed 4,699 times
1

m0nhawk
- 22,980
- 9
- 45
- 73

Son Nguyen Vu
- 13
- 1
- 3
-
It sounds like you need to convert the number from a float to an integer. Have a look at [this stack overflow question](http://stackoverflow.com/a/3387715/6049581) – Frits Apr 15 '17 at 08:56
3 Answers
1
You could use the Decimal
module. However in your specific case, you can avoid the problem by multiplying both numerator and divisor by the same number so to make the divisor an integer, like this:
(1350*10)/(2.7*10)
which is of course the same as:
13500/27

trincot
- 317,000
- 35
- 244
- 286
0
That is a representation error, see https://docs.python.org/2/tutorial/floatingpoint.html#representation-error
you can check if it is 500.00 with
eps=1.0e-10
if abs(1350/2.7-500) < eps:
...
Or, just use round(number[, ndigits])

frank
- 103
- 10