Skip to content

Commit

Permalink
Updated quantile to use sorted values for min and max
Browse files Browse the repository at this point in the history
  • Loading branch information
sanjayginde committed Nov 22, 2024
1 parent f7aeeb4 commit ef7f828
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/statistics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
Expand Down
8 changes: 8 additions & 0 deletions test/statistics-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit ef7f828

Please sign in to comment.