Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

floating point in python gives a wrong answer

I calculated the following:

>>> float(10.0-9.2)
0.800000000000000*7*

even doing 10.0-9.2 gave the above result. Why is the extra 7 coming in the result?

I'm on python 3.2.

like image 768
Rohan Avatar asked May 01 '12 19:05

Rohan


2 Answers

Floating point arithmetic has built-in problems as it's based on a binary approximation of numbers.

There is a good explanation of this in the Python docs.

You can check out the decimal module if you need more exact answers.

like image 168
Gareth Latty Avatar answered Oct 20 '22 00:10

Gareth Latty


You can use round()

for example:

print(round(10 - 9.2, 2))
like image 30
Ali Bayat Mokhtari Avatar answered Oct 20 '22 00:10

Ali Bayat Mokhtari