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
Could Any one explain why is this so? Thanks
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
Could Any one explain why is this so? Thanks
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