stats.percentile
Percentile of a list of numbers by a named method: nearest-rank, or linear interpolation (R-7, Excel PERCENTILE.INC).
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 24 tests, run in TypeScript, Python and Rust.
What it does
"The 95th percentile" is not one number: statistics packages disagree, and Hyndman and Fan catalogue nine definitions. This capability makes the caller name the one they mean.
- `nearest-rank`: the smallest value with at least p% of the sample at or below it. Rank = ceil(p/100 x n), and p = 0 gives the minimum. The answer is always a member of the list, which is what SLAs usually mean by "p95 latency". This is Hyndman and Fan's type 1 (the inverse of the empirical distribution function). - `linear`: interpolate between the two closest ranks at position h = (n - 1) x p/100 (zero-based), giving x[floor h] + (h - floor h) x (x[floor h + 1] - x[floor h]). This is Hyndman and Fan's type 7, the default in R (`quantile(type = 7)`) and NumPy (`method="linear"`), and Excel's `PERCENTILE.INC` (with p as a fraction there).
For example
percentile(15, 20, 35, 40, 50, 5, nearest-rank, 2)→ 15 nearest-rank 5th percentile of 15,20,35,40,50 is 15 (rank ceil 0.25 = 1)percentile(15, 20, 35, 40, 50, 30, nearest-rank, 2)→ 20 nearest-rank 30th percentile is 20 (rank ceil 1.5 = 2)percentile(15, 20, 35, 40, 50, 40, nearest-rank, 2)→ 20 nearest-rank 40th percentile is 20 (rank exactly 2, not 3)
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
export function percentile(values: readonly number[], p: number, method: PercentileMethod, decimals: number): number
| values | float[] | the sample, in any order, at least one value |
| p | float | 0 to 100; 95 is the 95th percentile |
| method | PercentileMethod | nearest-rank returns a member of the list; linear interpolates |
| decimals | int | 0 to 12; the result is rounded half away from zero to this many places |
| returns | float |
The type it declares, generated into your project
export type PercentileMethod = "nearest-rank" | "linear";
Your code names it in one line, in the file that uses it
import { percentile } from "#fune/stats.percentile@^1";
import { type PercentileMethod } from "./stats_percentile_types.ts";
const POW10 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12];
// Half away from zero on the binary64 value, then -0 becomes 0. Only floor,
// * and / are used, so every language rounds the same double the same way.
function roundTo(x: number, decimals: number): number {
const scale = POW10[decimals];
const y = Math.abs(x) * scale;
let r = Math.floor(y);
if (y - r >= 0.5) r += 1;
const out = r / scale;
return (x < 0 ? -out : out) + 0;
}
/**
* The p-th percentile of `values` by a named method.
*
* There is no single "95th percentile": the caller names the definition, so
* a dashboard and a billing job cannot quietly disagree.
*/
export function percentile(values: readonly number[], p: number, method: PercentileMethod, decimals: number): number {
if (!Array.isArray(values)) throw new TypeError("values must be a list of numbers");
if (values.length === 0) throw new RangeError("values must not be empty");
for (const v of values) {
if (typeof v !== "number" || !Number.isFinite(v)) {
throw new TypeError(`values must be finite numbers, received ${v}`);
}
}
if (typeof p !== "number" || !Number.isFinite(p) || p < 0 || p > 100) {
throw new RangeError(`p must be between 0 and 100, received ${p}`);
}
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 12) {
throw new RangeError(`decimals must be a whole number from 0 to 12, received ${decimals}`);
}
const sorted = [...values].sort((a, b) => a - b);
const n = sorted.length;
let result: number;
if (method === "nearest-rank") {
// The smallest value with at least p% of the sample at or below it.
let rank = Math.ceil((p * n) / 100);
if (rank < 1) rank = 1;
result = sorted[rank - 1];
} else if (method === "linear") {
// Hyndman & Fan type 7: zero-based position (n - 1) * p / 100.
const h = ((n - 1) * p) / 100;
const lo = Math.floor(h);
if (lo >= n - 1) {
result = sorted[n - 1];
} else {
result = sorted[lo] + (h - lo) * (sorted[lo + 1] - sorted[lo]);
}
} else {
throw new RangeError(`unknown percentile method "${method}"`);
}
return roundTo(result, decimals);
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add stats.percentile
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./stats.percentile-1.0.0-typescript.fune, or fetch it from a terminal with fune pull stats.percentile@1.0.0:typescript.
The whole function, every language, is one file too: stats.percentile-1.0.0.fune, 15,267 bytes, sha256 b848e49f013fc86b77acac0821b654c86dea0c1b880a47fd9afe2fdaeac9b79c. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before stats.percentile
after — your function gets the result and the arguments, and returns the final result.
// fune: after stats.percentile
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show stats.percentile --steps.
// fune: step stats.percentile after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| nearest-rank 5th percentile of 15,20,35,40,50 is 15 (rank ceil 0.25 = 1) | 15, 20, 35, 40, 50, 5, nearest-rank, 2 | → | 15 |
| nearest-rank 30th percentile is 20 (rank ceil 1.5 = 2) | 15, 20, 35, 40, 50, 30, nearest-rank, 2 | → | 20 |
| nearest-rank 40th percentile is 20 (rank exactly 2, not 3) | 15, 20, 35, 40, 50, 40, nearest-rank, 2 | → | 20 |
| nearest-rank 50th percentile is 35 | 15, 20, 35, 40, 50, 50, nearest-rank, 2 | → | 35 |
| nearest-rank sorts unsorted input first | 50, 15, 40, 20, 35, 100, nearest-rank, 2 | → | 50 |
| nearest-rank 0th percentile is the minimum | 50, 15, 40, 20, 35, 0, nearest-rank, 2 | → | 15 |
| nearest-rank 90th of 1..10 is 9 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 90, nearest-rank, 0 | → | 9 |
| linear 40th percentile interpolates 60% of the way from 20 to 35 | 15, 20, 35, 40, 50, 40, linear, 6 | → | 29 |
| linear 75th of 1,2,3,4 matches Excel PERCENTILE.INC(...,0.75) = 3.25 | 4, 3, 2, 1, 75, linear, 2 | → | 3.25 |
| linear 90th of 1..10 is 9.1 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 90, linear, 6 | → | 9.1 |
Show the other 14 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| linear 0th and 100th are the minimum and maximum | -7.5, 3, 12.25, 100, linear, 2 | → | 12.25 |
| linear 0th is the minimum | -7.5, 3, 12.25, 0, linear, 2 | → | -7.5 |
| a single value is every percentile | 42, 37.5, linear, 3 | → | 42 |
| a half rounds away from zero (Python round() would give 0) | 0, 1, 50, linear, 0 | → | 1 |
| a negative half rounds away from zero | -1, 0, 50, linear, 0 | → | -1 |
| 2.5 rounds up to 3, not to the even 2 | 2, 3, 50, linear, 0 | → | 3 |
| just under a half rounds down | 1, 2, 3, 10, linear, 0 | → | 1 |
| decimals keep the stated places | 1, 2, 33, linear, 2 | → | 1.33 |
| an empty sample is an error | , 50, linear, 2 | → | error: values must not be empty |
| p above 100 is an error | 1, 2, 101, linear, 2 | → | error: p must be between 0 and 100 |
| negative p is an error | 1, 2, -1, nearest-rank, 2 | → | error: p must be between 0 and 100 |
| an unknown method is an error | 1, 2, 50, midpoint, 2 | → | error: unknown percentile method "midpoint" |
| decimals above 12 is an error | 1, 2, 50, linear, 13 | → | error: decimals must be a whole number from 0 to 12 |
| a non-number value is an error | 1, 2, 50, linear, 2 | → | error: values must be finite numbers |
More from the author
Both methods give the minimum at p = 0 and the maximum at p = 100. The input is sorted numerically on a copy and never mutated.
**Precision.** The result is rounded to `decimals` places, half away from zero, applied to the binary64 value: y = |x| x 10^decimals, r = floor(y), plus one if y - r >= 0.5, divided back by 10^decimals, with the sign restored. So 0.5 rounds to 1 and -0.5 to -1 (Python's `round()` would give 0), and -0 is returned as 0.
**Why the three languages agree to the bit.** Only IEEE-754 addition, subtraction, multiplication, division and floor are used, in the same order in every language, and each of those is correctly rounded by the standard. No library function whose last bit can differ between platforms (exp, log, sin) is involved, so the unrounded result is the same double everywhere and the rounding step cannot split them. Position and rank are computed as (n - 1) x p / 100 and p x n / 100, in that order.
Sources: R. J. Hyndman and Y. Fan, "Sample Quantiles in Statistical Packages", The American Statistician 50(4), 1996, pp. 361-365; Microsoft, "PERCENTILE.INC function" (support.microsoft.com); NIST/SEMATECH e-Handbook of Statistical Methods, section 7.2.6.2 "Percentiles".
Files
| Path | Bytes |
|---|---|
| README.md | 2,080 |
| impl/python.py | 2,525 |
| impl/rust.rs | 2,949 |
| impl/typescript.ts | 2,257 |
| vectors.json | 3,011 |