📊 Calculates the value below which the given fraction of the data falls.
Syntax
import { quantile } from '@opentf/std'; quantile<T>( arr: T[], p: number, cb?: (val: T, index: number) => number, ): number;
Parameters
| Name | Type | Description |
|---|---|---|
| arr | T[] | The source array. |
| p | number | The fraction, from 0 to 1. |
| cb | Function | Iteratee invoked per element to pick the number. |
Returns
The quantile, or NaN if there are no values. Throws a RangeError if p is not a number from 0 to 1.
p runs from 0 to 1, so a 95th percentile is quantile(values, 0.95). 0 gives the minimum, 1 the maximum and 0.5 the median — the same value median returns, by construction.
Which method?
A quantile rarely lands on an observation, so the two either side of it are interpolated linearly: with n values, position (n - 1) * p is taken and the fraction between the neighbouring values applied.
This is the default of R's quantile, NumPy's percentile and Excel's PERCENTILE.INC — the method usually meant by "the 95th percentile". It is one of nine in common use, though, and a figure produced by another will differ on small samples.
Examples
quantile([1, 2, 3, 4], 0.25) //=> 1.75 quantile([1, 2, 3, 4], 0.5) //=> 2.5 quantile([1, 2, 3, 4], 0.75) //=> 3.25
The p95 of a set of response times:
quantile(requests, 0.95, (r) => r.durationMs);