EN
TypeScript - weighted arithmetic mean
0
points
In this article, we would like to show you how to calculate the weighted arithmetic mean value in TypeScript.
Runnable example:
const calculateWeightedAverage = (values: number[], weights: number[]): number => {
if (values.length !== weights.length) {
throw new Error('Values and weights arrays must have same size.');
}
let a = 0;
let b = 0;
for (let i = 0; i < values.length; ++i) {
const weight = weights[i];
a += weight * values[i];
b += weight;
}
return a / b;
};
// Usage example:
// Let's suppose we have: 4x 3.0, 9x 4.0 and 4x 5.0
const marks: number[] = [3.0, 4.0, 5.0];
const counts: number[] = [4, 9, 4];
const average: number = calculateWeightedAverage(marks, counts);
console.log(average);
Output:
4