Possible duplicate:
Python rounding error with floating point numbers
Python errors are incorrect
I cannot get Python to correctly subtract 1 - 0.8 and assign it. He continues to come up with the wrong answer, 0.1999999999999999996.
I learned a little:
sq = {} sub = {} for i in range(1000): sq[str(i/1000.)+'**2']=((i/1000.)**2) sub['1-'+str(i/1000.)]=(1.0-(i/1000.))
and found that this error occurs with a somewhat random group of floats from 0 to 1 to the third decimal place. A similar error also occurs when you round these floats, but with a different subset.
I hope to explain this and how to make Python the correct arithmetic. Using round(x,3) is a workaround I'm using now, but it's not elegant.
Thanks!
This is a session in my Python 2.7.3 shell:
*** Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32. *** *** Remote Python engine is active *** >>> 1-0.8 0.19999999999999996 >>> print 1-0.8 0.2 >>> a = 1-0.8 >>> a 0.19999999999999996 >>> print a 0.2 >>> a = 0.2 >>> print a 0.2 >>> a 0.2 >>>
Here is the code I put in a couple of online translators:
def doit(): d = {'a':1-0.8} return d print doit()
and conclusion:
{'a': 0.19999999999999996}
python arithmetic-expressions subtraction
gotube
source share