Median calculation gives dodgy result

Posted By: johnnyp

Median calculation gives dodgy result - 09/18/17 21:43

Code:
var a[4] = {1, 4, 3, 5};
printf("n%f", Median(a, 4));
printf("n%f", Percentile(a, 4, 50));

# output
4.500000
4.500000



Unless I am much mistaken the median value should be 3.5

Median() always gives the right answer when length is even, and never when length is odd.
Posted By: flare9x

Re: Median calculation gives dodgy result - 09/19/17 00:06

Interesting - may have a bug there.

I tested in R:

Code:
x <- c(1,3,4,5)
median(x)
[1] 3.5



Can you try maybe the R bridge, maybe the R function can calculate it correctly?
Posted By: jcl

Re: Median calculation gives dodgy result - 09/19/17 09:55

I would also expect that the median in that example is 3.5 and not 4.5. The Median function calls the Percentile function and the Percentile function is from some statistics library. Maybe that library does not consider even lengths. I'll forward that to the developers to check.
Posted By: johnnyp

Re: Median calculation gives dodgy result - 09/19/17 12:53

I wrote my own version of Percentile.

Code:
var percentile(vars data, int length, var percent)
{
	int* ids = sortIdx(data, length);
	var pos = (length-1)*percent/100;
	var below = data[ids[min(length-1, (int)pos)]];
	if(pos == round(pos))
		return below;
	var above = data[ids[min(length-1, (int)pos+1)]];
	return (below+above)/2;
}

© 2024 lite-C Forums