-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgeneralized_mean.go
42 lines (38 loc) · 986 Bytes
/
generalized_mean.go
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
42
package statistics
import (
"math"
"github.com/theriault/maths"
)
// GeneralizedMean
//
// Time complexity: O(n)
// Space complexity: O(1)
//
// https://en.wikipedia.org/wiki/Generalized_mean
func GeneralizedMean[A maths.Integer | maths.Float](X []A, p float64) float64 {
// as p approaches 0, the general mean equals the geometric mean
if p == 0 {
return GeometricMean(X...)
}
// as p approaches negative infinity, the general mean equals the minimum
if p == math.Inf(-1) {
return float64(Min(X...))
}
// as p approaches positive infinity, the general mean equals the maximum
if p == math.Inf(+1) {
return float64(Max(X...))
}
// if X is empty, return NaN
if len(X) == 0 {
return math.NaN()
}
sum := PowerSum(X, p)
if sum == 0 {
return math.NaN()
}
return math.Pow(sum/float64(len(X)), float64(1)/p)
}
// PowerMean is an alias for GeneralizedMean
func PowerMean[A maths.Integer | maths.Float](X []A, p float64) float64 {
return GeneralizedMean(X, p)
}