python 十进制给出了错误的答案
python decimal gives wrong answers
这是你可以在解释器中尝试的东西,谁能解释一下为什么?
注意:这个问题与 Is floating point math broken? 不同,因为我的答案不是有点偏离,而是偏离的很远,我的问题是关于小数,而不是关于内置的浮点数。
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 - a
是 0.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
这是你可以在解释器中尝试的东西,谁能解释一下为什么? 注意:这个问题与 Is floating point math broken? 不同,因为我的答案不是有点偏离,而是偏离的很远,我的问题是关于小数,而不是关于内置的浮点数。
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 - a
是 0.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