How to Calculate Variance With JavaScript


By onjsdev

Variance is a tool used in statistics to measure how spread out the numbers are in a group. It helps to show how different each number is from the average (or mean) of the group.

In this article we will show you how to calculate variance with javascript for a given array consisting of numbers. Let's get started.

CALCULATE VARIANCE WITH JAVASCRIPT

You can see the formula below for calculating the variance of a dataset.

Formula: V = (Σ(x - μ)^2 / n)

Where:

  • x is a data in array,
  • μ is the mean,
  • n is the length of the array,
  • Σ is the sum of

In the following example, we will utilize an array containing numbers, and the following JavaScript array methods will be applied to compute various portions of the formula.

  • Math.pow => Square
  • map => (x - μ)^2
  • reduce => calculating mean and Σ((x - μ)^2)

A Note: Sample vs Population In Variance

When we want to calculate the variance for a sample that is taken for entire data(population), the formula will undergo a minor modification, as follows:

Formula: V = (Σ(x - μ)^2 / (n-1))

And here is a code snippet calculating the variance of an array.

// A Dataset
const numbers = [1, 2, 3, 4, 5];

// Calculate mean
const mean = numbers.reduce((acc, curr) => acc + curr) / numbers.length;

// For the sample numbers.length - 1
const length = numbers.length;

const v =
  numbers
    .map((number) => Math.pow(number - mean, 2))
    .reduce((acc, curr) => acc + curr) / length;

console.log(v); // 2

Conclusion

In conclusion, variance is usefeul measure that indicate variability in a data set and we have shown how to calculate it with javascript using array methods and math library.

Thank you for reading.