How to fix error with decimal numbers in Python?

Viewed 440

I have program which generates table which I need. When difference between numbers was enough large(about 5 points), everything was ok. So I decided to use Decimal library. But when I added that module to the program, everything was broken(numbers were the same). Here is my output(few start lines) with Decimal

0.00402787895809813677877597726251   0.00402787895809813677877597726251
0.00402787895809813677877597726251   0.00402787895809813677877597726251
0.00402787895809813677877597726251   0.00402787895809813677877597726251

As you can see they are the same, however base numbers are different. How to fix that bug?

from decimal import *
getcontext().prec = 30
ls = [1,4,2,1,1,1,2,1,1,1,1,1,1,1,1,2]
#N = Decimal(22)
l = Decimal(0.0040278789580981364238)
r = Decimal(0.0040278789580981370940)
one = Decimal(r-l)/Decimal(22)
print(len(ls))
for elem in ls:
    print(Decimal(l),'\t',Decimal(l)+Decimal(one)*Decimal(elem))
    l+=Decimal(one)*Decimal(elem)
1 Answers

You need to construct Decimals from strings, not floats:

>>> from decimal import Decimal
>>> Decimal(0.0040278789580981370940)
Decimal('0.004027878958098136778775977262512242305092513561248779296875')
>>> Decimal(0.0040278789580981364238)
Decimal('0.004027878958098136778775977262512242305092513561248779296875')
>>> Decimal("0.0040278789580981370940")
Decimal('0.0040278789580981370940')
>>> Decimal("0.0040278789580981364238")
Decimal('0.0040278789580981364238')

Floats have limited precision, which means that both 0.0040278789580981370940 and 0.0040278789580981364238 are "rounded" to the same number internally (more details on why this is unavoidable, see Floating Point Arithmetic: Issues and Limitations).

>>> 0.0040278789580981364238
0.004027878958098137
>>> 0.0040278789580981370940
0.004027878958098137

If you use a string as the contructor, a Decimal can be built with arbitrary precision.

Related