find the variance of a list of numbers in javascript

To find the variance of a list of numbers in javascript, you can use the following formula:

index.tsx
variance = sum((x - mean)^2) / n
33 chars
2 lines

Where x is each number in the list, mean is the average of the list, and n is the total number of elements in the list.

Here's an example implementation of this formula in javascript:

index.tsx
function calculateVariance(numbers) {
  const mean = numbers.reduce((acc, val) => acc + val, 0) / numbers.length;
  const variance = numbers.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / numbers.length;
  return variance;
}

const numbers = [1, 2, 3, 4, 5];
const variance = calculateVariance(numbers);
console.log("Variance:", variance); // Output: Variance: 2
373 chars
10 lines

In this example, we first calculate the mean of the numbers using the reduce function. We then calculate the variance using another reduce function that iterates over each number in the list and sums up the squared difference between that number and the mean. Finally, we divide the sum by the total number of elements in the list to get the variance.

gistlibby LogSnag