2
votes

Here is my input:

>>> from decimal import Decimal
>>> Decimal('114.3')
Decimal('114.3')
>>> Decimal(114.3)
Decimal('114.2999999999999971578290569595992565155029296875')

I thought those two instances of Decimal have to be equal but Decimal with float arg seems to loose precision. Why is this? My python version is 2.7.3. Thanks in advance!

2

2 Answers

2
votes

The second line is giving you the exact decimal value of the binary floating-point number which approximates 114.3. This is almost all about binary floating point, not much about Decimal. See the docs for details.

Later: if using Python 3, see these docs instead. Same basic thing, but Python 3 has more tools to help you explore cases "like this".

3
votes

When you do Decimal(114.3), you are creating a regular float object and then passing it to Decimal. The accuracy is lost due to binary floating-point imprecision when the float 114.3 is created, before Decimal ever gets to see it. There's no way to get that accuracy back. That's why Decimal accepts string representations as input, so it can see what you actually typed and use the right level of precision.