fix Median operation returns incorrect result for unsorted odd-length inputs (#2284)
This commit is contained in:
parent
ddbe914132
commit
f0468d391d
@ -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)];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
33
tests/operations/tests/Median.mjs
Normal file
33
tests/operations/tests/Median.mjs
Normal 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"],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
Loading…
x
Reference in New Issue
Block a user