Skip to main content
 首页 » 编程设计

python之如何处理 python math.ceil 中的舍入错误

2025年05月04日33lexus

以下代码片段的结果是 6:

import math 
number = (1 - 0.99) * 500 
math.ceil(number) 

虽然(数学上)正确答案是 5。大概这是一个舍入问题 - 实现正确解决方案的最佳方法是什么?

请您参考如下方法:

Presumably this is a rounding problem

是的:

>>> 1 - 0.99 
0.010000000000000009 
>>> (1 - 0.99) * 500 
5.000000000000004 

what is the best way to enforce the correct solution?

你可以使用 decimal.Decimal而不是 float:

>>> from decimal import Decimal 
>>> import math 
>>> (1 - Decimal("0.99")) * 500 
Decimal('5.00') 
>>> math.ceil((1 - Decimal("0.99")) * 500) 
5.0