Weighted Mean
Install and import#
npm install fintech-algorithmsimport { weightedMean } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/weighted-mean";Signature#
weightedMean(input)Computes a weighted average of values using the parallel weights series, dividing the sum of value-times-weight products by the total weight.
Parameters#
| Name | Type | Notes |
|---|---|---|
input | { values: number[]; weights: number[] } | values holds the observations and weights the importance attached to each one, position by position. Both are coerced with Number and must be finite; the weights are not normalised for you, the function divides by their sum.weights: same length as `values`, and the weights must not sum to zero |
Returns#
{ weightedMean: number; weightSum: number }
weightedMean is the weighted average and weightSum is the denominator that was used, which is what tells you whether the weights were proportions or raw counts.
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 - When
weightsis missing, empty, or holds a non-finite entry — throws RangeError - When
weightsandvaluesdiffer in length, or the weights sum to exactly zero — 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#
weightedMean(input)Returns#
object with 2 fields: weightedMean, weightSum
{
"weightedMean": 3.3333333333333335,
"weightSum": 6
}Diagrams#
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#
- average
- Historical-example decision