Median and Mode
Install and import#
npm install fintech-algorithmsimport { medianAndMode } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/median-and-mode";Signature#
medianAndMode(input)Reports the middle of a numeric series and its most frequent values, tallying exact equality so a tie produces several modes rather than one arbitrary winner.
Parameters#
| Name | Type | Notes |
|---|---|---|
input | { values: number[] } | The observations to summarise, under the key values. Modes are counted on exact numeric equality after Number coercion, so 2 and 2.0 are the same value. |
Returns#
{ median: number; modes: number[]; modeFrequency: number }
median is the 0.5 quantile by linear interpolation between order statistics, modes lists every value attaining the highest count in ascending order, and modeFrequency is that highest count.
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#
medianAndMode(input)Returns#
object with 2 fields: median, modes
{
"median": 2,
"modes": [2]
}Diagrams#
Calculation flow#
Reasoning flow — D00-F04-A04
flowchart LR
A["Finite observations"] --> B["Name units and scope"]
B --> C["Freeze: median = middle ordered value(s); mode set = {x : frequency(x) is maximal}"]
C --> D["Calculate full precision"]
D --> E{"Boundary satisfied?"}
E -->|Yes| F["Report median 2 · modes [2] · mode frequency 2"]
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#
- Measures of Location
- Historical-example decision