如何正确舍入半浮点数? [英] How to properly round-up half float numbers?

查看:46
本文介绍了如何正确舍入半浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临 round() 函数的奇怪行为:

 for i in range(1, 15, 2):n = i/2打印(n,=>",轮(n))

此代码打印:

0.5 =>01.5 =>22.5 =>23.5 =>44.5 =>45.5 =>66.5 =>6

我希望浮点值总是向上取整,但它被四舍五入到最接近的偶数.

为什么会出现这种行为,获得正确结果的最佳方法是什么?

我尝试使用 fractions 但是结果是一样的.

解决方案

数值类型部分明确记录了这种行为:

<块引用>

round(x[, n])
x 四舍五入到 n 位,四舍五入到偶数.如果省略 n,则默认为 0.

注意四舍五入到偶数.这也称为银行家舍入;通过四舍五入到最接近的偶数数,而不是总是向上或向下四舍五入(复合四舍五入误差),您可以平均四舍五入误差.

如果您需要更多地控制舍入行为,请使用 decimal 模块,它可以让您准确指定舍入策略应该采用什么使用.

例如,从一半向上取整:

<预><代码>>>>从十进制导入本地上下文,十进制,ROUND_HALF_UP>>>使用 localcontext() 作为 ctx:... ctx.rounding = ROUND_HALF_UP...对于范围内的 i (1, 15, 2):... n = 十进制(i)/2...打印(n,'=>',n.to_integral_value())...0.5 =>11.5 =>22.5 =>33.5 =>44.5 =>55.5 =>66.5 =>7

I am facing a strange behavior of the round() function:

for i in range(1, 15, 2):
    n = i / 2
    print(n, "=>", round(n))

This code prints:

0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6

I expected the floating values to be always rounded up, but instead, it is rounded to the nearest even number.

Why such behavior, and what is the best way to get the correct result?

I tried to use the fractions but the result is the same.

解决方案

The Numeric Types section documents this behaviour explicitly:

round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.

Note the rounding half to even. This is also called bankers rounding; instead of always rounding up or down (compounding rounding errors), by rounding to the nearest even number you average out rounding errors.

If you need more control over the rounding behaviour, use the decimal module, which lets you specify exactly what rounding strategy should be used.

For example, to round up from half:

>>> 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

这篇关于如何正确舍入半浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆