-2

I just check following thing in python 2.7

print 0.1 + 0.2

output :- 0.3

print 0.1 + 0.2 - 0.3

output :- 5.55111512313e-17

But I expect the 0.0 So, how to achive this thing ?

cool
  • 3
  • 2
  • possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – MattDMo Oct 16 '14 at 19:22

1 Answers1

1

The problem here is that the float type doesn't have enough precision to display the result you want. If you try to print the partial sum 0.1 + 0.2 you'll see that the float result you get is 0.30000000000000004.

So, 5.55111512313e-17 is the closest approximation possible with float type variables to that result. If you try to cast the result to int, so:

int(0.2 + 0.1 - 0.3)

You'll see 0, and that's the right integer approximation. You can get 0.0 with floating point variables by using the decimal class.

Try this:

from decimal import Decimal
Decimal("0.2") + Decimal("0.1") - Decimal("0.3")

And you'll see that the result is Decimal("0.0")

Sergio0694
  • 4,065
  • 1
  • 22
  • 47