-
Notifications
You must be signed in to change notification settings - Fork 1
/
analytics.go
38 lines (34 loc) · 949 Bytes
/
analytics.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
package metrics
import "math"
// Expectation computes an estimate of the population mean from a finite sample.
func Expectation(data []float64) float64 {
Σ := 0.0
for _, x := range data {
Σ += x
}
return Σ / float64(len(data))
}
// Variance computes an estimate of the population variance from a finite
// sample. The estimate is unbiased. The computation is based on the
// compensated-summation version of the two-pass algorithm.
//
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Two-pass_algorithm
func Variance(data []float64) float64 {
n, μ := float64(len(data)), Expectation(data)
Σ1, Σ2 := 0.0, 0.0
for _, x := range data {
Δ := x - μ
Σ1 += Δ
Σ2 += Δ * Δ
}
return (Σ2 - Σ1*Σ1/n) / (n - 1.0)
}
// L2 computes the Euclidean distance between two vectors.
func L2(x, y []float64) float64 {
sum := 0.0
for i := range x {
Δ := x[i] - y[i]
sum += Δ * Δ
}
return math.Sqrt(sum)
}