如何正确地收集在Python中的半浮点数? [英] How to properly round up half float numbers in Python?
问题描述
<$ c (1,15,2):
n = i / 2
print(n,=>,round(n))
$ c
$ b $ p
$ p $0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
我预计浮动值总是四舍五入,但取而代之的是四舍五入到最近偶数。
为什么这样的行为,以及得到正确结果的最好方法是什么?
尝试使用 分数
但是结果是一样的。 数字类型部分明确地记录了这种行为:
round(x [,n])
x 四舍五入到n位,四舍五入到平均。如果省略了n,那么它默认为0.
注意舍入一半甚至。这也被称为银行家四舍五入;而不是总是舍入或舍入(舍入舍入误差),通过四舍五入到最接近的偶数你平均舍入误差。
如果你需要更多的控制舍入行为,使用 十进制
模块,它可以让你指定使用哪个舍入策略。
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.
这篇关于如何正确地收集在Python中的半浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!