python - 如何正确舍入半 float ?

标签 python python-3.x floating-point rounding precision

我正面临 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/

相关文章:

python - pandas:如何通过比较其他列值来修改数据框中的列中的值

python - 如何替换Django模板中的某些特定字符?

python - 在 CrawlSpider 中将 cookie 传递给后续请求

python - 如何延迟打印一行一行的多行字符串?

Java DecimalFormat,是否可以在小数部分进行分组?

c++ - C++ 中 float_max + 1 是如何定义的?

SQL设置浮点精度

python - Python 中的模幂算法

python - Python:响应命令行提示符

python - django bootstrap 4 导航栏切换按钮在本地主机上不起作用