-
Notifications
You must be signed in to change notification settings - Fork 224
/
harmonic_mean.js
41 lines (36 loc) · 1.29 KB
/
harmonic_mean.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* The [Harmonic Mean](https://en.wikipedia.org/wiki/Harmonic_mean) is
* a mean function typically used to find the average of rates.
* This mean is calculated by taking the reciprocal of the arithmetic mean
* of the reciprocals of the input numbers.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @returns {number} harmonic mean
* @throws {Error} if x is empty
* @throws {Error} if x contains a negative number
* @example
* harmonicMean([2, 3]).toFixed(2) // => '2.40'
*/
function harmonicMean(x) {
if (x.length === 0) {
throw new Error("harmonicMean requires at least one data point");
}
let reciprocalSum = 0;
for (let i = 0; i < x.length; i++) {
// the harmonic mean is only valid for positive numbers
if (x[i] <= 0) {
throw new Error(
"harmonicMean requires only positive numbers as input"
);
}
reciprocalSum += 1 / x[i];
}
// divide n by the reciprocal sum
return x.length / reciprocalSum;
}
export default harmonicMean;