在 python 中使用十进制模块时,似乎除法仍然给出不准确的结果。这是我用来检查的代码,我做错了什么还是不可能用十进制模块准确地进行除法?在那种情况下,我可以用其他东西来准确地进行这种计算吗?
from decimal import Decimal as D a = D('39.37007874') b = D('0.0254') c = D('1') print(c / a) #0.02540000000010160000000040640 unexpected print(c / b) #39.37007874015748031496062992 unexpected print(c * b) #0.0254 expected print(c * a) #39.37007874 expected
您可以简单地使用 round 函数并获得所需的任意数量的小数。
from decimal import Decimal as D a = D('39.37007874') b = D('0.0254') c = D('1') print(round(c / a, 8)) #0.02540000 print(round(c / b, 8)) #39.37007874 print(round(c * b, 8)) #0.02540000 print(round(c * a, 8)) #39.37007874