简体   繁体   中英

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 . You can set it with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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