Ask Your Question

# Find median of [2, 5, 2, 6, 7, 3, 7, 5, 7, 0, 6, 10]

Ok, I'm encountering this weird result when performing:

l = [2, 5, 2, 6, 7, 3, 7, 5, 7, 0, 6, 10]
r = median(l)


The r becomes 11/2 which is 5.5. The median here is clearly an integer and it is 5!

Why does it return 5.5?

edit retag close merge delete

## Comments

The list has length 12 (even). I think what sage is returning is the average of elements at positions 6 and 7, which are 5 and 6.

( 2015-07-10 14:26:28 -0500 )edit

## 2 answers

Sort by ยป oldest newest most voted
if hasattr(v, 'median'): return v.median()

if len(v) == 0:
# Median of empty set defined as NaN
return NaN
values = sorted(v)
if len(values) % 2 == 1:
return values[((len(values))+1)/2-1]
else:
lower = values[(len(values)+1)/2-1]
upper = values[len(values)/2]
return (lower + upper)/ZZ(2)

more

## Comments

For completeness: "If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values..." see https://en.wikipedia.org/wiki/Median

( 2015-07-11 01:55:41 -0500 )edit

How do you guys read the answer? I don't understand this. I am new to this website.

more

## Comments

See the comment under the answer - I posted the code itself but the comment is probably easier to get!

( 2015-07-25 08:06:39 -0500 )edit

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2015-07-10 13:56:30 -0500

Seen: 7,546 times

Last updated: Jul 22 '15