Skip to content

weightedMean

weightedMean(x, weights): number

Defined in: src/weighted_mean.js:23

The weighted mean, also known as weighted average, is the sum of each value multiplied by its weight, divided by the total weight.

The weighted values are accumulated with the same Kahan-Babuska correction that sum uses, so that terms which cancel do not lose precision. The correction is applied in a single pass, without building an intermediate array.

This runs in O(n), linear time, with respect to the length of the array.

number[]

sample of one or more data points

number[]

non-negative weights for each data point

number

weighted mean

if x is empty, weights is a different length than x, all weights are zero, or a weight is negative

weightedMean([80, 90, 100], [1, 1, 2]); // => 92.5