以下代码片段的结果是 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
