We know that 0.1 + 0.1 + 0.1 - 0.3 = 0.0
But in python 0.1 + 0.1 + 0.1 - 0.3 = 5.5511151231257827e-017
Is there any way I can get 0.0...??
We know that 0.1 + 0.1 + 0.1 - 0.3 = 0.0
But in python 0.1 + 0.1 + 0.1 - 0.3 = 5.5511151231257827e-017
Is there any way I can get 0.0...??
Well a simple fix would be to multiply everything by 10. Ie:
import os
print float(1+1+1-3)/10
os.system("pause")
To be at sure side add in beginning of your numeric Python 2 code:
from __future__ import division
This makes 1/4 produce 0.25, not 0 (integer division). For integer division use // operator.
Start with this documentation page http://docs.python.org/tutorial/floatingpoint.html.
A problem is that python's 0.1 is not the mathematical 0.1 because 0.1 can not be represented exactly as a machine binary number.
The limits of floating point numbers
http://www.lahey.com/float.htm
http://docs.python.org/tutorial/floatingpoint.html
Use decimal for more precision.
from decimal import Decimal as dec
# 0.1 + 0.1 + 0.1 - 0.3 = 0.0
x = dec("0.1")
y = dec("0.3")
print x + x + x - y
Thank you very much everyone... Now i understand the reason behind it... Thank you!