Python 中的小数模数不准确

Decimal module in Python inaccurate

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

实际输出:

3.141592653589793115997963468544185161590576171875

输出应该是:

3.141592653589793238462643383279502884197169399373

为什么值会改变?

您传递的是 floating-point number to the Decimal constructor, and floating-point numbers are inherently imprecise (see also the Python manual).

要将精确数字传递给 Decimal 构造函数,请将其作为字符串传递。

>>> from decimal import Decimal

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

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

如果你有一个 floating-point 变量,你可以先将它转换为字符串,然后再转换为 Decimal 以避免 some floating-point 不精确:

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

如果您需要完全精确,只需使用小数即可:

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

您应该将字符串传递给 Decimal(),而不是浮点数,浮点数一开始就是不精确的。另外,请注意 Python 文档

中的以下内容

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