fix Median operation returns incorrect result for unsorted odd-length inputs (#2284)

This commit is contained in:
Willi Ballenthin 2026-06-20 09:21:07 +02:00 committed by GitHub
parent ddbe914132
commit f0468d391d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 5 deletions

View File

@ -108,14 +108,17 @@ export function mean(data) {
* @returns {BigNumber} * @returns {BigNumber}
*/ */
export function median(data) { export function median(data) {
if ((data.length % 2) === 0 && data.length > 0) { if (data.length > 0) {
data.sort(function(a, b) { data.sort(function(a, b) {
return a.minus(b); return a.minus(b);
}); });
const first = data[Math.floor(data.length / 2)];
const second = data[Math.floor(data.length / 2) - 1]; if ((data.length % 2) === 0) {
return mean([first, second]); const first = data[Math.floor(data.length / 2)];
} else { const second = data[Math.floor(data.length / 2) - 1];
return mean([first, second]);
}
return data[Math.floor(data.length / 2)]; return data[Math.floor(data.length / 2)];
} }
} }

View File

@ -0,0 +1,33 @@
/**
* Median operation tests.
*
* @author copilot-swe-agent[bot]
* @copyright Crown Copyright 2018
* @license Apache-2.0
*/
import TestRegister from "../../lib/TestRegister.mjs";
TestRegister.addTests([
{
name: "Median: odd-length input",
input: "10 1 2",
expectedOutput: "2",
recipeConfig: [
{
op: "Median",
args: ["Space"],
},
],
},
{
name: "Median: even-length input",
input: "10 1 2 5",
expectedOutput: "3.5",
recipeConfig: [
{
op: "Median",
args: ["Space"],
},
],
},
]);