Skip to main content
Module

x/statistics/src/sample_variance.ts

Deno basic statistics module.
Latest
File
import { sumNthPowerDeviations } from "./sum_nth_power_deviations.ts";
/** * 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 {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 */export function sampleVariance(x: number[]): number { // The variance of no numbers is null 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;}