Hello I was trying to determine if a element of a given list was part of the second half of the list. For example if it had 7 elements
my_list = ['a','b','c','d','e','f','g']
my function would only return True for elements ‘e’, ‘f’ and ‘g’.
The solution was pretty simple:
def fashionably_late(arrivals, name): return (arrivals.index(name) + 1 > round(len(arrivals)/2))
My solution had a bug though because of how rounding works, I just want to understand why
However this behavior from python is perplexing, why is 7/2 (i.e 3.5 ) rounded to 4 the same way as 9/2 (i.e. 4.5) to 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
As a side note I am aware of the math.ceil()
function.
Advertisement
Answer
From the docs
if two multiples are equally close, rounding is done toward the even choice (so, for example, both
round(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
)
This convention is often called statistician’s rounding, as it produces more accurate results over large aggregate data (always rounding up on 0.5 increases the average of the data by 0.5, but rounding either way using a consistent rule keeps the mean more consistent, on aggregate)