为什么在Python中,round(1/2)返回0,而round(7/2)返回4

  • 本文关键字:round 返回 Python python
  • 更新时间 :
  • 英文 :


你好,我试图确定给定列表的元素是否是列表后半部分的一部分。例如,如果它有7个元素

my_list = ['a','b','c','d','e','f','g']

my函数只会为元素"e"、"f"one_answers"g"返回True。

解决方案非常简单:

def fashionably_late(arrivals, name):

return (arrivals.index(name) + 1 > round(len(arrivals)/2))

我的解决方案有一个错误,但由于舍入的工作方式,我只想了解为什么

然而,python的这种行为令人困惑,为什么7/2(即3.5(四舍五入到4与9/2(即4.5(到4的方式相同。

for i in range(1,11):
print(i , round(i/2))
​
1 0
2 1
3 2
4 2
5 2
6 3
7 4
8 4
9 4
10 5
#The way I expect it to work is: 
for i in range(1,11):
print(i , i//2 + i %2)
​
1 1
2 1
3 2
4 2
5 3
6 3
7 4
8 4
9 5
10 5

顺便说一句,我知道math.ceil()的功能。

从文档

如果两个倍数相等,则向偶数选择进行舍入(例如,round(0.5)round(-0.5)都是0round(1.5)2(

这种约定通常被称为统计学家取整,因为它在大的聚合数据上产生更准确的结果(总是在0.5上取整会使数据的平均值增加0.5,但使用一致规则的任何一种取整方式都会使平均值在聚合上保持更一致(

嗯,我也很担心,但根据这里的

Python中的

Round((函数遵循半到偶数的舍入策略。在这种策略中,数字四舍五入到最接近的偶数整数例如,如果我们需要将7.5取整,它将被取整关闭到其最近的偶数整数8。4.5将四舍五入到最接近的EVEN整数,因此为4。

您可以尝试:

for i in range(10):
print(f"{i}/2={i/2} => round{i/2}={round(i/2)}")

你会看到:

0/2=0.0 => round(0.0)=0
1/2=0.5 => round(0.5)=0
2/2=1.0 => round(1.0)=1
3/2=1.5 => round(1.5)=2
4/2=2.0 => round(2.0)=2
5/2=2.5 => round(2.5)=2
6/2=3.0 => round(3.0)=3
7/2=3.5 => round(3.5)=4
8/2=4.0 => round(4.0)=4
9/2=4.5 => round(4.5)=4

出于您的目的,您可以添加一个小数字epsilon=1e-6来根据您的需要更改round((行为:

epsilon=1e-6
for i in range(10):
print(f"round({i/2}+epsilon)={round(epsilon+i/2)}")

然后你会有:

round(0.0+epsilon)=0
round(0.5+epsilon)=1
round(1.0+epsilon)=1
round(1.5+epsilon)=2
round(2.0+epsilon)=2
round(2.5+epsilon)=3
round(3.0+epsilon)=3
round(3.5+epsilon)=4
round(4.0+epsilon)=4
round(4.5+epsilon)=5

享受吧!

查看如何正确地将半浮点数取整?。

这个问题是由这样一个事实引起的,即在数学中,精确地舍入0.5有点武断,并且对如何做到这一点有不同的意见。Python遵循的策略是,更喜欢舍入偶数。

最新更新