Ask Your Question
0

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

asked 9 years ago

AnAccDev gravatar image

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?

Preview: (hide)

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.

fidbc gravatar imagefidbc ( 9 years ago )

2 Answers

Sort by » oldest newest most voted
2

answered 9 years ago

kcrisman gravatar image
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)
Preview: (hide)
link

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

rws gravatar imagerws ( 9 years ago )
0

answered 9 years ago

Mellie gravatar image

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

Preview: (hide)
link

Comments

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

kcrisman gravatar imagekcrisman ( 9 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 9 years ago

Seen: 7,832 times

Last updated: Jul 23 '15