我正面临 round()
函数的奇怪行为:
for i in range(1, 15, 2):
n = i / 2
print(n, "=>", round(n))
此代码打印:
0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
我希望浮点值总是向上取整,但相反,它被四舍五入到最接近的偶数。
为什么会出现这种行为,获得正确结果的最佳方法是什么?
我尝试使用 fractions
但结果是一样的。
最佳答案
Numeric Types section明确记录此行为:
round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
注意四舍五入到偶数。这也称为银行家四舍五入;而不是总是向上或向下舍入(复合舍入误差),通过舍入到最接近的 偶数 数来平均舍入误差。
如果您需要对舍入行为进行更多控制,请使用 decimal
module ,它可以让您准确指定 rounding strategy should be used .
例如,从一半向上取整:
>>> from decimal import localcontext, Decimal, ROUND_HALF_UP
>>> with localcontext() as ctx:
... ctx.rounding = ROUND_HALF_UP
... for i in range(1, 15, 2):
... n = Decimal(i) / 2
... print(n, '=>', n.to_integral_value())
...
0.5 => 1
1.5 => 2
2.5 => 3
3.5 => 4
4.5 => 5
5.5 => 6
6.5 => 7
关于python - 如何正确舍入半 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33019698/