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 3,629 times
1
m0nhawk
- 21,912
- 9
- 42
- 71
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
- 263,463
- 30
- 215
- 251
-
NB: I see you tried to accept more than one answer: this is not possible. You can only mark one answer as accepted. When you have a bit more reputation you'll be able to upvote answers -- where there is no such limitation. – trincot Apr 15 '17 at 06:40
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