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 e773310
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 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
17 changes: 11 additions & 6 deletions test/statistics-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
// (c) Mathigon
// =============================================================================

import tape from "tape";
import { mode, quantile } from "../src";

import tape from 'tape';
import {mode, quantile} from '../src';


tape('mode', (test) => {
tape("mode", (test) => {
test.equal(mode([]), undefined);
test.equal(mode([2]), 2);
test.equal(mode([2, 3]), undefined);
Expand All @@ -19,7 +17,7 @@ tape('mode', (test) => {
test.end();
});

tape('quantile', (test) => {
tape("quantile", (test) => {
test.equal(quantile([], 0.5), 0);

const evenPopulation = [1, 2, 3, 4, 5];
Expand All @@ -35,5 +33,12 @@ 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 e773310

Please sign in to comment.