Python error in main subtraction?

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} 
+8
python arithmetic-expressions subtraction
source share
3 answers

Floating numbers do not work as you would expect from them.

To get started, read the floating point guide . In short: computers represent floating point numbers as binary, and it turns out that saving the exact decimal fraction as binary is not possible ( try this for yourself on paper to see why). For practical purposes, 0.19999999999999996 is "close enough" to 0.2. If you want to print it as 0.2, you can do something like:

 print "%0.1f" % floating_point_value 

So what you see is not a mistake. It expected behavior.

+8
source share

Use Decimal , which is just for this:

 >>> from decimal import Decimal, getcontext >>> Decimal(1) - Decimal(0.8) Decimal('0.1999999999999999555910790150') >>> getcontext().prec = 3 >>> Decimal(1) - Decimal(0.8) Decimal('0.200') >>> float(Decimal(1) - Decimal(0.8)) 0.2 
+8
source share

Python stores floats with "bits", and some floats you simply cannot represent exactly, no matter how many precision bits you have. This is the problem you have here. This is like trying to write 1/3 in decimal format with a limited number of decimal places exactly.

+1
source share

All Articles