繁体   English   中英

python十进制给出错误的答案

[英]python decimal gives wrong answers

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM