gpt4 book ai didi

python - Python 中的十进制模块不准确

转载 作者:行者123 更新时间:2023-12-05 01:24:06 25 4
gpt4 key购买 nike

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

实际输出:

3.141592653589793115997963468544185161590576171875

输出应该是:

3.141592653589793238462643383279502884197169399373

为什么值会改变?

最佳答案

您正在传递 floating-point number到 Decimal 构造函数,和 floating-point numbers are inherently imprecise (另请参见 the Python manual)。

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

>>> from decimal import Decimal

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

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

如果您有一个浮点变量,您可以先将其转换为字符串,然后再转换为 Decimal 以避免一些浮点不精确:

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

如果您需要完全精确,只需一直使用 Decimals:

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

关于python - Python 中的十进制模块不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71661286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com