Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error in basic subtraction? [duplicate]

Tags:

Possible Duplicate:
Python rounding error with float numbers
python maths is wrong

I can't get Python to correctly do the subtraction 1 - 0.8 and assign it. It keeps coming up with the incorrect answer, 0.19999999999999996.

I explored a bit:

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 discovered that this error happens with a somewhat random group of the floats between 0 and 1 to the third decimal place. A similar error also occurs when you square those floats, but to a different subset.

I'm hoping for an explanation of this and how to make Python do the arithmetic right. Using round(x,3) is the work-around I'm using for 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's the code I put into a couple online interpreters:

def doit():
    d = {'a':1-0.8}
    return d

print doit()

and the output:

{'a': 0.19999999999999996}
like image 301
gotube Avatar asked Jan 02 '13 10:01

gotube


People also ask

How do you subtract two floats in Python?

To subtract two floating numbers in Python, use the subtract operator(-). Float is one of the most used numeric data types in Python.

How do you subtract two values in Python?

I have defined a function called subtraction as def subtraction(a,b): To subtract the numbers, I have used sub=a-b. The function is returned as return sub. To get the output, I have used print(“Result is: “,subtraction(number1,number2)).

What is the subtraction function in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.


1 Answers

Use Decimal its designed 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
like image 53
Burhan Khalid Avatar answered Oct 20 '22 11:10

Burhan Khalid