-
Notifications
You must be signed in to change notification settings - Fork 224
/
sample_variance.js
36 lines (31 loc) · 1.45 KB
/
sample_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
28
29
30
31
32
33
34
35
36
import sumNthPowerDeviations from "./sum_nth_power_deviations.js";
/**
* The [sample variance](https://en.wikipedia.org/wiki/Variance#Sample_variance)
* is the sum of squared deviations from the mean. The sample variance
* is distinguished from the variance by the usage of [Bessel's Correction](https://en.wikipedia.org/wiki/Bessel's_correction):
* instead of dividing the sum of squared deviations by the length of the input,
* it is divided by the length minus one. This corrects the bias in estimating
* a value from a set that you don't know if full.
*
* References:
* * [Wolfram MathWorld on Sample Variance](http://mathworld.wolfram.com/SampleVariance.html)
*
* @param {Array<number>} x a sample of two or more data points
* @throws {Error} if the length of x is less than 2
* @return {number} sample variance
* @example
* sampleVariance([1, 2, 3, 4, 5]); // => 2.5
*/
function sampleVariance(x) {
if (x.length < 2) {
throw new Error("sampleVariance requires at least two data points");
}
const sumSquaredDeviationsValue = sumNthPowerDeviations(x, 2);
// this is Bessels' Correction: an adjustment made to sample statistics
// that allows for the reduced degree of freedom entailed in calculating
// values from samples rather than complete populations.
const besselsCorrection = x.length - 1;
// Find the mean value of that list
return sumSquaredDeviationsValue / besselsCorrection;
}
export default sampleVariance;