Functional Weave
Code in Python

stats.percentile

Percentile of a list of numbers by a named method: nearest-rank, or linear interpolation (R-7, Excel PERCENTILE.INC).

2.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 29 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.

def percentile(values: Sequence[float], p: float, method: PercentileMethod, decimals: int) -> float
valuesfloat[]the sample, in any order, at least one value
pfloat0 to 100; 95 is the 95th percentile
methodPercentileMethodnearest-rank returns a member of the list; linear interpolates
decimalsint0 to 12; the result is rounded half away from zero, on the exact value of the double, to this many places
returnsfloat

The type it declares, generated into your project

PercentileMethod = Literal["nearest-rank", "linear"]

Your code names it in one line, in the file that uses it

from fune.stats.percentile import percentile  # stats.percentile@^2
impl/python.py · 55 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import math
from typing import Sequence

from .math_round_float import round_float  ← from math.round-float ^1.0.0 · built alongside by fune
from .stats_percentile_types import PercentileMethod


def _finite(value: object) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)


def percentile(values: Sequence[float], p: float, method: PercentileMethod, decimals: int) -> float:
    """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.
    """
    if isinstance(values, (str, bytes)) or not isinstance(values, (list, tuple)):
        raise TypeError("values must be a list of numbers")
    if len(values) == 0:
        raise ValueError("values must not be empty")
    for v in values:
        if not _finite(v):
            raise TypeError("values must be finite numbers, received %r" % (v,))
    if not _finite(p) or p < 0 or p > 100:
        raise ValueError("p must be between 0 and 100, received %r" % (p,))
    # Checked up front as well as in round_float (same wording), so a bad
    # decimals is reported before the method is looked at, as in 1.x.
    if isinstance(decimals, bool) or not isinstance(decimals, int) or decimals < 0 or decimals > 12:
        raise ValueError("decimals must be a whole number from 0 to 12, received %r" % (decimals,))

    # float() first so integer inputs follow exactly the binary64 path the
    # other languages take.
    ordered = sorted(float(v) for v in values)
    n = len(ordered)
    p = float(p)

    if method == "nearest-rank":
        # The smallest value with at least p% of the sample at or below it.
        rank = math.ceil((p * n) / 100.0)
        if rank < 1:
            rank = 1
        result = ordered[rank - 1]
    elif method == "linear":
        # Hyndman & Fan type 7: zero-based position (n - 1) * p / 100.
        h = ((n - 1) * p) / 100.0
        lo = math.floor(h)
        if lo >= n - 1:
            result = ordered[n - 1]
        else:
            result = ordered[lo] + (h - lo) * (ordered[lo + 1] - ordered[lo])
    else:
        raise ValueError('unknown percentile method "%s"' % (method,))
    # math.round-float rounds on the exact value of the double: 2.675 gives 2.67.
    return round_float(result, decimals)

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Python 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
Download for Python stats.percentile-2.0.0-python.fune · 11,612 bytes sha256 bb85b30925fa7f80c8c290f25e84ec3920fae0c1455c706ee8f21693c02dbd9f

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./stats.percentile-2.0.0-python.fune, or fetch it from a terminal with fune pull stats.percentile@2.0.0:python.

The whole function, every language, is one file too: stats.percentile-2.0.0.fune, 16,571 bytes, sha256 4693d39eb07fa564946633d58010c57ca84c722206051c511be28ab988b4f316. 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 — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace math.round-float in stats.percentile

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.

CaseArgumentsExpected
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 19 tests
CaseArgumentsExpected
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
halfway between 2.6 and 2.75 is the double 2.67499999..., so it rounds to 2.67 (1.x gave 2.68) 2.75, 2.6, 50, linear, 2 → 2.67
the negative of that rounds to -2.67 (1.x gave -2.68) -2.75, -2.6, 50, linear, 2 → -2.67
nearest-rank returns the member 2.675, which rounds to 2.67 (1.x gave 2.68) 9, 2.675, 1.5, 50, nearest-rank, 2 → 2.67
1.45 is stored just below the tie, so it rounds to 1.4 at one place (1.x gave 1.5) 1.45, 0, 100, linear, 1 → 1.4
8.345 is stored just above the tie, so it still rounds up to 8.35 8.345, 50, nearest-rank, 2 → 8.35
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 (0 to 12) by `math.round-float`: half away from zero, decided on the exact value of the double. So 0.5 rounds to 1 and -0.5 to -1 (Python's `round()` would give 0), -0 is returned as 0, and 2.675, which is stored as 2.67499999999999982..., rounds to 2.67 at two places.

**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, `math.round-float`, which is itself bit-identical in all three, cannot split them. Position and rank are computed as (n - 1) x p / 100 and p x n / 100, in that order.

## Changes in 2.0.0

2.0.0 rounds on the exact value of the double, so a percentile of 2.675 now gives 2.67 at two places. 1.x rounded the scaled product instead (floor of |x| x 10^decimals, compared with a half), and 2.675 x 100 is exactly 267.5 in floating point, so 1.x said 2.68. The private rounding helper is gone: this version requires `math.round-float ^1.0.0` and rounds with it, so every float capability in the registry rounds alike.

None of the 1.x vectors changed answers (each was recomputed from the exact value of its double). New vectors pin the difference: the linear 50th percentile of 2.6 and 2.75 gives 2.67 (1.x 2.68), of -2.75 and -2.6 gives -2.67 (1.x -2.68), the nearest-rank member 2.675 gives 2.67 (1.x 2.68), and 1.45 at one place gives 1.4 (1.x 1.5); 8.345, stored just above its tie, still gives 8.35.

`decimals` is still 0 to 12, and still refused up front with the same message ("decimals must be a whole number from 0 to 12"), before the method is looked at, as in 1.x.

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

PathBytes
README.md3,158
impl/python.py2,331
impl/rust.rs2,701
impl/typescript.ts2,061
vectors.json3,753