简体   繁体   English

十进制 Python 库有奇怪的行为

[英]Decimal Python Library has weird behavior

I'm trying to fix all my calculation by using Python Decimal.我正在尝试使用 Python 十进制来修复我的所有计算。 I'm limiting the decimal places to 3, nevertheless, I'm getting this behavior:我将小数位限制为 3,但是,我得到了这种行为:

from decimal import *
getcontext().prec = 3

In [0]:Decimal('32.983') - Decimal('0.000')
Out[1]: Decimal('33.0')

Does anyone know how to overcome that?有谁知道如何克服它? I would like to get:我想得到:

Out[1]: Decimal('32.983')

If you want to get 32.983 , then you would need to set the precision to 5, not 3. Precision is the count of significant digits, not the count of digits after the decimal point.如果要获得32.983 ,则需要将精度设置为 5,而不是 3。精度是有效数字的计数,而不是小数点后的位数。

You shouldn't normally put a drastic limit on the precision of intermediate computations, since that will affect the accuracy of the final result.您通常不应该对中间计算的精度进行严格限制,因为这会影响最终结果的准确性。 You can always round the final result for display.您始终可以将最终结果四舍五入以进行显示。

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

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