0

I am adding two numbers in python.

A = 29.000988000000003
B = 10

in python A+B gives 39.00098800000001.

Can someone explain me what exactly is going on? According to me the last digit should be 3 not 1. Even with B = 10.0 also gives same results..

Basically I want to know what is the machine accuracy of python and how I can avoid such incidents?

greole
  • 4,523
  • 5
  • 29
  • 49

2 Answers2

0

I highly recommend reading this:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

If you want to avoid such problems, please look at decimal python module:

https://docs.python.org/2/library/decimal.html

For example:

>>> from decimal import *
>>> getcontext().prec = 17
>>> a = Decimal('29.000988000000003')
>>> b = Decimal('10')
>>> a + b
Decimal('39.000988000000003')
Matt
  • 222
  • 1
  • 7
0

quote from the doc:

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

https://docs.python.org/2/tutorial/floatingpoint.html

bpceee
  • 416
  • 4
  • 17