UNPKG

1.22 kBJavaScriptView Raw
1import combineMeans from "./combine_means";
2
3/**
4 * When combining two lists of values for which one already knows the variances,
5 * one does not have to necessary recompute the variance of the combined lists
6 * in linear time. They can instead use this function to compute the combined
7 * variance by providing the variance, mean & number of values of the first list
8 * and the variance, mean & number of values of the second list.
9 *
10 * @since 3.0.0
11 * @param {number} variance1 variance of the first list
12 * @param {number} mean1 mean of the first list
13 * @param {number} n1 number of items in the first list
14 * @param {number} variance2 variance of the second list
15 * @param {number} mean2 mean of the second list
16 * @param {number} n2 number of items in the second list
17 * @returns {number} the combined mean
18 *
19 * @example
20 * combineVariances(14 / 3, 5, 3, 8 / 3, 4, 3); // => 47 / 12
21 */
22function combineVariances(variance1, mean1, n1, variance2, mean2, n2) {
23 const newMean = combineMeans(mean1, n1, mean2, n2);
24
25 return (
26 (n1 * (variance1 + Math.pow(mean1 - newMean, 2)) +
27 n2 * (variance2 + Math.pow(mean2 - newMean, 2))) /
28 (n1 + n2)
29 );
30}
31
32export default combineVariances;