1

I am very new to the python and playing around the print statement and found something unexpected.

print(0.3 + 0.1==0.4)

ANS : True

but when I tried

print(0.2 + 0.1==0.3)

ANS : False

enter image description here

Could Any one explain why is this so? Thanks

1 Answers1

2

This is due to floating point math, not Python's print statement. You can see this for yourself if you go into the Python REPL.

>>> .2 + .1
0.30000000000000004
>>> .3 + .1
0.4

When comparing floating point numbers, always use an epsilon:

epsilon = 1E-6
print(0.3 - (0.2 + 0.1) < epsilon)  # prints True
dogman288
  • 613
  • 3
  • 9