Percentiles, Quantiles, and Quartiles
Install and import#
npm install fintech-algorithmsimport { percentilesQuantilesAndQuartiles } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles";Signature#
percentilesQuantilesAndQuartiles(input)Returns the three quartiles of a numeric series and the interquartile range between the first and third, using linear interpolation between neighbouring order statistics.
Parameters#
| Name | Type | Notes |
|---|---|---|
input | { values: number[] } | The observations to cut into quantiles, under the key values. The series is sorted internally, so the caller's order does not matter. |
Returns#
{ quantiles: { '0.25': number; '0.5': number; '0.75': number }; iqr: number }
quantiles is keyed by the three cut points as strings, and iqr is the 0.75 quantile minus the 0.25 quantile.
Errors#
- When
inputis null, an array, or not an object — throws TypeError - When
valuesis missing, is not an array, or is empty — throws RangeError - When any entry of
valuesdoes not coerce to a finite number — throws RangeError
Complexity: time O(n log n),
space O(n).
Worked example#
verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.
Input#
{
"values": [1, 2, 2, 4, 9],
"weights": [1, 1, 2, 1, 1],
"trimProportion": 0.2,
"bins": 4
}Call#
percentilesQuantilesAndQuartiles(input)Returns#
object with 2 fields: quantiles, iqr
{
"quantiles": {
"0.25": 2,
"0.5": 2,
"0.75": 4
},
"iqr": 2
}Diagrams#
Calculation flow#
Reasoning flow — D00-F04-A06
flowchart LR
A["Finite observations"] --> B["Name units and scope"]
B --> C["Freeze: Type 7: h = 1 + (n−1)q; linearly interpolate between ordered positions around h"]
C --> D["Calculate full precision"]
D --> E{"Boundary satisfied?"}
E -->|Yes| F["Report Q1 2 · median 2 · Q3 4 · IQR 2 (type 7)"]
E -->|No| G["Abstain and repair contract"]
F --> H["Pair with distribution context"]
How it works#
This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.
References#
- Percentile Definitions
- percentile
- Sample Quantiles in Statistical Packages
- Historical-example decision