Languages
[Edit]
EN

TypeScript - weighted arithmetic mean

0 points
Created by:
a_horse
538

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

See also

  1. JavaScript - weighted arithmetic mean

References

  1. Weighted arithmetic mean - Wikipedia

Alternative titles

  1. TypeScript - weighted arithmetic average
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join