forked from simple-statistics/simple-statistics
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsample_variance.js
More file actions
40 lines (34 loc) · 1.55 KB
/
sample_variance.js
File metadata and controls
40 lines (34 loc) · 1.55 KB
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
37
38
39
40
'use strict';
/* @flow */
var sumNthPowerDeviations = require('./sum_nth_power_deviations');
/**
* 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 /*: Array<number> */)/*:number*/ {
// The variance of no numbers is null
if (x.length < 2) {
throw new Error('sampleVariance requires at least two data points');
}
var 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.
var besselsCorrection = x.length - 1;
// Find the mean value of that list
return sumSquaredDeviationsValue / besselsCorrection;
}
module.exports = sampleVariance;