stat.median not using sorted array
charlesw opened this issue · comments
Like your implementation however I noticed that median is currently just returning the median element of the unsorted array not the sorted array and is thus giving incorrect results:
The current implementation:
export function median (arr) {
if (arr.length < 2) return arr[0];
var sorted = arr.slice().sort(compare);
if (sorted.length % 2 === 0) {
// even
return (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
}
else {
// odd
return arr[(arr.length - 1) / 2];
}
Proposed fix:
export function median (arr) {
if (arr.length < 2) return arr[0];
var sorted = arr.slice().sort(compare);
if (sorted.length % 2 === 0) {
// even
return (sorted [sorted .length / 2 - 1] + sorted [sorted .length / 2]) / 2;
}
else {
// odd
return sorted [(sorted .length - 1) / 2];
}
Thanks for reporting this Charles, it's fixed in v0.2.0.