我刚刚重读了Python 3.0的新特性,它说:

round()函数的舍入策略和返回类型已更改。 精确的中间情况现在四舍五入到最接近的偶数结果代替 远离0的。(例如,round(2.5)现在返回2而不是 3)。

和 round的文档:

对于支持round()的内置类型,值舍入为 10的- n次方最接近的倍数;如果两个倍数是 同样接近,四舍五入是对偶数的选择

因此,在v2.7.3中:

In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0

正如我所预料的。然而,现在在v3.2.3下:

In [32]: round(2.5)
Out[32]: 2

In [33]: round(3.5)
Out[33]: 4

这似乎有违直觉,与我的理解相悖 四舍五入(肯定会绊倒人)。英语不是我的母语,但是 直到我读到这篇文章,我以为我知道四舍五入的意思:-/我确定 在v3被引入的时候,肯定有一些讨论 但在我的寻找中,我找不到一个好的理由。

有人知道为什么这个变成了这个吗? 有没有其他主流编程语言(例如,C, c++, Java, Perl, ..)做这种类型的舍入(对我来说不一致)?

我错过了什么?

更新:@Li-aungYip关于“银行家的舍入”的评论给了我正确的搜索词/关键字来搜索,我发现了这个SO问题:为什么。net使用银行家的舍入作为默认值?,所以我会仔细阅读。


当前回答

Python 3。X将.5值舍入为偶数的相邻值

assert round(0.5) == 0
assert round(1.5) == 2
assert round(2.5) == 2

import decimal

assert decimal.Decimal('0.5').to_integral_value() == 0
assert decimal.Decimal('1.5').to_integral_value() == 2
assert decimal.Decimal('2.5').to_integral_value() == 2

但是,如果需要,可以将十进制舍入“向后”更改为始终向上舍入。5:

decimal.getcontext().rounding = decimal.ROUND_HALF_UP

assert decimal.Decimal('0.5').to_integral_value() == 1
assert decimal.Decimal('1.5').to_integral_value() == 2
assert decimal.Decimal('2.5').to_integral_value() == 3

i = int(decimal.Decimal('2.5').to_integral_value()) # to get an int
assert i == 3
assert type(i) is int

其他回答

我建议自定义函数,它将工作于DataFrame:

def dfCustomRound(df, dec):
    d = 1 / 10 ** dec
    df = round(df, dec + 2)
    return (((df % (1 * d)) == 0.5 * d).astype(int) * 0.1 * d * np.sign(df) + df).round(dec)

Python 3中的舍入行为。

小数点后15位加1。 精度可达15位。

round2=lambda x,y=None: round(x+1e-15,y)

某些情况下:

in: Decimal(75.29 / 2).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
in: round(75.29 / 2, 2)
out: 37.65 GOOD

in: Decimal(85.55 / 2).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
in: round(85.55 / 2, 2)
out: 42.77 BAD

修复:

in: round(75.29 / 2 + 0.00001, 2)
out: 37.65 GOOD
in: round(85.55 / 2 + 0.00001, 2)
out: 42.78 GOOD

如果你想要更多的小数,例如4,你应该加上(+ 0.0000001)。

为我工作。

# round module within numpy when decimal is X.5 will give desired (X+1)

import numpy as np
example_of_some_variable = 3.5
rounded_result_of_variable = np.round(example_of_some_variable,0)
print (rounded_result_of_variable)

Python 3中最简单的舍入方法。学校教的X使用辅助变量:

n = 0.1 
round(2.5 + n)

这些将是2.0到3.0系列的结果(0.1步):

>>> round(2 + n)
>>> 2

>>> round(2.1 + n)
>>> 2

>>> round(2.2 + n)
>>> 2

>>> round(2.3 + n)
>>> 2

>>> round(2.4 + n)
>>> 2

>>> round(2.5 + n)
>>> 3

>>> round(2.6 + n)
>>> 3

>>> round(2.7 + n)
>>> 3

>>> round(2.8 + n)
>>> 3

>>> round(2.9 + n)
>>> 3

>>> round(3 + n)
>>> 3