Ask Your Question
0

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

asked 2015-07-10 20:56:30 +0100

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?

edit retag flag offensive 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.

fidbc gravatar imagefidbc ( 2015-07-10 21:26:28 +0100 )edit

2 Answers

Sort by ยป oldest newest most voted
2

answered 2015-07-11 00:02:33 +0100

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)
edit flag offensive delete link 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

rws gravatar imagerws ( 2015-07-11 08:55:41 +0100 )edit
0

answered 2015-07-23 02:33:33 +0100

Mellie gravatar image

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

edit flag offensive delete link more

Comments

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

kcrisman gravatar imagekcrisman ( 2015-07-25 15:06:39 +0100 )edit

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: 2015-07-10 20:56:30 +0100

Seen: 7,795 times

Last updated: Jul 23 '15