-
Notifications
You must be signed in to change notification settings - Fork 224
/
log_average.js
30 lines (27 loc) · 965 Bytes
/
log_average.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
/**
* The [log average](https://en.wikipedia.org/wiki/https://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_logarithms)
* is an equivalent way of computing the geometric mean of an array suitable for large or small products.
*
* It's found by calculating the average logarithm of the elements and exponentiating.
*
* @param {Array<number>} x sample of one or more data points
* @returns {number} geometric mean
* @throws {Error} if x is empty
* @throws {Error} if x contains a negative number
*/
function logAverage(x) {
if (x.length === 0) {
throw new Error("logAverage requires at least one data point");
}
let value = 0;
for (let i = 0; i < x.length; i++) {
if (x[i] < 0) {
throw new Error(
"logAverage requires only non-negative numbers as input"
);
}
value += Math.log(x[i]);
}
return Math.exp(value / x.length);
}
export default logAverage;