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