-
Notifications
You must be signed in to change notification settings - Fork 224
/
variance.js
27 lines (24 loc) · 907 Bytes
/
variance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sumNthPowerDeviations from "./sum_nth_power_deviations.js";
/**
* The [variance](http://en.wikipedia.org/wiki/Variance)
* is the sum of squared deviations from the mean.
*
* This is an implementation of variance, not sample variance:
* see the `sampleVariance` method if you want a sample measure.
*
* @param {Array<number>} x a population of one or more data points
* @returns {number} variance: a value greater than or equal to zero.
* zero indicates that all values are identical.
* @throws {Error} if x's length is 0
* @example
* variance([1, 2, 3, 4, 5, 6]); // => 2.9166666666666665
*/
function variance(x) {
if (x.length === 0) {
throw new Error("variance requires at least one data point");
}
// Find the mean of squared deviations between the
// mean value and each value.
return sumNthPowerDeviations(x, 2) / x.length;
}
export default variance;