Ask Your Question
0

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

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

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 14:26:28 -0500 )edit

2 answers

Sort by ยป oldest newest most voted
2

answered 2015-07-10 17:02:33 -0500

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 01:55:41 -0500 )edit
0

answered 2015-07-22 19:33:33 -0500

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 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

Question Tools

Stats

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

Seen: 7,258 times

Last updated: Jul 22 '15