Search code examples
pythondecimalpi

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

  • 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')