'Decimal module in Python inaccurate

from decimal import *
Pi=Decimal(3.141592653589793238462643383279502884197169399373)
print(Pi)

Actual output:

3.141592653589793115997963468544185161590576171875

Output should be:

3.141592653589793238462643383279502884197169399373

Why does the value change?



Solution 1:[1]

You're passing in a floating-point number to the Decimal constructor, and floating-point numbers are inherently imprecise (see also the Python manual).

To pass in a precise number to the Decimal constructor, pass it in as a string.

>>> from decimal import Decimal

# bad
>>> Decimal(3.141592653589793238462643383279502884197169399373)
Decimal('3.141592653589793115997963468544185161590576171875')

# good
>>> Decimal('3.141592653589793238462643383279502884197169399373')
Decimal('3.141592653589793238462643383279502884197169399373')

If you have a floating-point variable, you can cast it to a string first, then to a Decimal to avoid some floating-point imprecision:

>>> a = 0.1 + 0.2
0.30000000000000004
>>> Decimal(a)
Decimal('0.3000000000000000444089209850062616169452667236328125')
>>> Decimal(str(a))
Decimal('0.30000000000000004')
>>>

If you need full precision, just work with Decimals all the way:

>>> Decimal("0.1") + Decimal("0.2")
Decimal('0.3')

Solution 2:[2]

You should pass a string to Decimal(), not a float, floats are imprecise to begin with. Also, note the following from the Python docs

Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem

from decimal import *
getcontext().prec = 100 #precision

pi = Decimal("3.141592653589793238462643383279502884197169399373")
print(pi)    #3.141592653589793238462643383279502884197169399373

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 alec_djinn