find the variance of a list of numbers in typescript

To find the variance of a list of numbers in TypeScript, we can use the following formula:

index.ts
variance = (1/n) * Σ(xi - μ)²
30 chars
2 lines

where:

  • n is the number of elements in the list
  • Σ means summation (add up all values in the parentheses)
  • xi is the i-th element of the list
  • μ is the mean of the list, calculated as (Σxi) / n

We can implement this formula in TypeScript as follows:

index.ts
function calculateVariance(numbers: number[]): number {
  const n = numbers.length;
  const mean = numbers.reduce((acc, val) => acc + val, 0) / n;
  const squaredDiffSum = numbers.reduce((acc, val) => acc + (val - mean) ** 2, 0);
  const variance = squaredDiffSum / n;
  return variance;
}
290 chars
8 lines

In this function, we first calculate the mean of the list using the reduce() method. We then calculate the sum of the squared differences between each element of the list and the mean, using another call to reduce(). Finally, we divide this sum by the number of elements in the list to get the variance.

We can call this function like this:

index.ts
const numbers = [1, 2, 3, 4, 5];
const variance = calculateVariance(numbers); // 2.5
85 chars
3 lines

This function works for any list of numbers, regardless of its length or content.

gistlibby LogSnag