From ef7f828abc4d3137c5057fca3455a2aa21979c9c Mon Sep 17 00:00:00 2001 From: Sanjay Ginde Date: Fri, 22 Nov 2024 16:43:30 -0500 Subject: [PATCH] Updated quantile to use sorted values for min and max Fixes #192 --- src/statistics.ts | 4 ++-- test/statistics-test.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/statistics.ts b/src/statistics.ts index fd34a4d..5295f3b 100755 --- a/src/statistics.ts +++ b/src/statistics.ts @@ -19,8 +19,8 @@ export function quantile(values: number[], p: number, method: number = 1): numbe if (!n) return 0; const sorted = values.slice(0).sort((a, b) => (a - b)); - if (p === 0) return values[0]; - if (p === 1) return values[n - 1]; + if (p === 0) return sorted[0]; + if (p === 1) return sorted[n - 1]; // See https://en.wikipedia.org/wiki/Quantile#Estimating_quantiles_from_a_sample if (![1, 2, 3].includes(method)) throw new RangeError('Invalid quantile method.'); diff --git a/test/statistics-test.ts b/test/statistics-test.ts index 073be26..1397089 100644 --- a/test/statistics-test.ts +++ b/test/statistics-test.ts @@ -35,5 +35,13 @@ tape('quantile', (test) => { test.equal(quantile(oddPopulation, 0.5), 3.5); test.equal(quantile(oddPopulation, 0.75), 5); test.equal(quantile(oddPopulation, 1), 6); + + const randomPopulation = [4, 1, 2, 6, 3, 5]; + test.equal(quantile(randomPopulation, 0), 1); + test.equal(quantile(randomPopulation, 0.25), 2); + test.equal(quantile(randomPopulation, 0.5), 3.5); + test.equal(quantile(randomPopulation, 0.75), 5); + test.equal(quantile(randomPopulation, 1), 6); + test.end(); });