简体   繁体   English

python十进制给出错误的答案

[英]python decimal gives wrong answers

This is something you can try in the interpreter, can anyone explain me why?这是你可以在解释器中尝试的东西,谁能解释我为什么? Note: This problem is different from Is floating point math broken?注意:这个问题不同于浮点数学是否被破坏? because my answers are not a little off, but way off and my question is about decimal, not about the built in float.因为我的答案不是有点偏离,而是偏离,我的问题是关于十进制,而不是关于内置浮点数。

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')

The default Decimal precision is 28 decimals, so you are loosing data, b - a is 0.1100010000000000000000010000 .默认Decimal精度为 28 位小数,因此您正在丢失数据, b - a0.1100010000000000000000010000 You can set it with getcontext().prec您可以使用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