gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:33 25 4
gpt4 key购买 nike

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

关于python - 如何处理 python math.ceil 中的舍入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com