Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal module in Python inaccurate [duplicate]

Tags:

python

decimal

pi

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

Actual output:

3.141592653589793115997963468544185161590576171875

Output should be:

3.141592653589793238462643383279502884197169399373

Why does the value change?

like image 478
abc bcd Avatar asked Mar 27 '26 09:03

abc bcd


1 Answers

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')
like image 118
AKX Avatar answered Mar 28 '26 23:03

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!