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.
pub fn percentile(values: &[f64], p: f64, method: &str, decimals: i64) -> f64
| 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
// PercentileMethod is a string in Rust, one of: "nearest-rank", "linear".
// Parameters take it as &str and results hold it as String.
Your code names it in one line, in the file that uses it
fune!(stats.percentile@^1); // then call percentile(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
const POW10: [f64; 13] = [
1.0, 10.0, 100.0, 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.
fn round_to(x: f64, decimals: usize) -> f64 {
let scale = POW10[decimals];
let y = x.abs() * scale;
let mut r = y.floor();
if y - r >= 0.5 {
r += 1.0;
}
let out = r / scale;
(if x < 0.0 { -out } else { out }) + 0.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.
///
/// # Panics
/// Panics on an empty list, a non-finite value, p outside 0..=100, an unknown
/// method, or decimals outside 0..=12.
pub fn percentile(values: &[f64], p: f64, method: &str, decimals: i64) -> f64 {
if values.is_empty() {
panic!("values must not be empty");
}
for v in values {
if !v.is_finite() {
panic!("values must be finite numbers, received {}", v);
}
}
if !p.is_finite() || p < 0.0 || p > 100.0 {
panic!("p must be between 0 and 100, received {}", p);
}
if !(0..=12).contains(&decimals) {
panic!("decimals must be a whole number from 0 to 12, received {}", decimals);
}
let mut sorted = values.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
let n = sorted.len();
let result = match method {
"nearest-rank" => {
// The smallest value with at least p% of the sample at or below it.
let mut rank = ((p * n as f64) / 100.0).ceil() as usize;
if rank < 1 {
rank = 1;
}
sorted[rank - 1]
}
"linear" => {
// Hyndman & Fan type 7: zero-based position (n - 1) * p / 100.
let h = ((n - 1) as f64 * p) / 100.0;
let lo = h.floor();
let i = lo as usize;
if i >= n - 1 {
sorted[n - 1]
} else {
sorted[i] + (h - lo) * (sorted[i + 1] - sorted[i])
}
}
other => panic!("unknown percentile method \"{}\"", other),
};
round_to(result, decimals as usize)
}
pub fn fune_vector(args: &[Value]) -> Value {
// Refuse what the typed signature cannot hold, with the wording TypeScript
// and Python use, rather than let the conversion below quietly change it.
for v in args[0].as_arr() {
if !matches!(v, Value::Int(_) | Value::Float(_)) {
panic!("values must be finite numbers, received {:?}", v);
}
}
let values: Vec<f64> = args[0].as_arr().iter().map(|v| v.as_f64()).collect();
Value::Float(percentile(
&values,
args[1].as_f64(),
args[2].as_str(),
args[3].as_i64(),
))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:
fune add stats.percentile
The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./stats.percentile-1.0.0-rust.fune, or fetch it from a terminal with fune pull stats.percentile@1.0.0:rust.
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 |