Describe the bug
The Median operation only sorts the input array when its length is even. For odd-length inputs it returns the middle element of the unsorted array, which is mathematically incorrect.
src/core/lib/Arithmetic.mjs, median() function, lines 84-93
export function median(data) {
if ((data.length % 2) === 0 && data.length > 0) {
data.sort(function(a, b) {
return a.minus(b);
});
const first = data[Math.floor(data.length / 2)];
const second = data[Math.floor(data.length / 2) - 1];
return mean([first, second]);
} else {
return data[Math.floor(data.length / 2)];
}
}
For odd-length arrays the function skips sorting entirely and returns data[Math.floor(data.length / 2)]. The median of any numeric set requires sorting first.
To Reproduce
add the Median operation with input 10,1,2 (comma delimiter). Expected output is 2 (the median of [1, 2, 10]); actual output is 1 (the middle element of the unsorted array).
Additional context
Suggested fix:
export function median(data) {
if (data.length === 0) {
return undefined;
}
data.sort(function(a, b) {
return a.minus(b);
});
if ((data.length % 2) === 0) {
const first = data[Math.floor(data.length / 2)];
const second = data[Math.floor(data.length / 2) - 1];
return mean([first, second]);
}
return data[Math.floor(data.length / 2)];
}
This sorts unconditionally, handles empty input by returning undefined, and preserves existing even-length behavior.
Describe the bug
The
Medianoperation only sorts the input array when its length is even. For odd-length inputs it returns the middle element of the unsorted array, which is mathematically incorrect.src/core/lib/Arithmetic.mjs,median()function, lines 84-93For odd-length arrays the function skips sorting entirely and returns
data[Math.floor(data.length / 2)]. The median of any numeric set requires sorting first.To Reproduce
add the
Medianoperation with input10,1,2(comma delimiter). Expected output is2(the median of [1, 2, 10]); actual output is1(the middle element of the unsorted array).Additional context
Suggested fix:
This sorts unconditionally, handles empty input by returning
undefined, and preserves existing even-length behavior.