Python Decimal 给出了错误的答案



这是你可以在解释器中尝试的东西,谁能解释我为什么? 注意:此问题不同于浮点数学是否损坏?因为我的答案不是有点偏差,而是很远,我的问题关于十进制,而不是关于内置的浮点数。

from decimal import getcontext, Decimal
a = Decimal(".110001"+"0"*17+"1"+"0"*95+"1"+"0"*599+"1"+"0"*4319+"1")
b = Decimal(".220002"+"0"*17+"2"+"0"*95+"2"+"0"*599+"2"+"0"*4319+"2")
b-a == a # Returns False while it should be True
b-a-a # Returns Decimal('-1.000000000000000000000000000E-120')

默认Decimal精度为 28 位小数,因此您丢失了数据,b - a0.1100010000000000000000010000。您可以使用getcontext().prec进行设置

a = Decimal(".110001" + "0" * 17 + "1" + "0" * 95 + "1" + "0" * 599 + "1" + "0" * 4319 + "1")
b = Decimal(".220002" + "0" * 17 + "2" + "0" * 95 + "2" + "0" * 599 + "2" + "0" * 4319 + "2")
getcontext().prec = max(len(str(a)), len(str(a)))
print(b-a == a) # True

最新更新