-
Notifications
You must be signed in to change notification settings - Fork 0
/
welford.go
58 lines (45 loc) · 939 Bytes
/
welford.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package welford
import "math"
type Welford struct {
n int
mean, cmean float64
sigma, csigma float64
}
func New() *Welford {
return &Welford{}
}
func (w *Welford) N() int {
return w.n
}
func (w *Welford) Mean() float64 {
return w.mean
}
func (w *Welford) Var() float64 {
if w.n == 0 {
return 0
}
return w.sigma / float64(w.n-1)
}
func (w *Welford) Stddev() float64 {
return math.Sqrt(w.Var())
}
func (w *Welford) Add(v ...float64) {
for i := range v {
w.add(v[i])
}
}
func (w *Welford) add(v float64) {
w.n++
oldm := w.mean
// naive
// w.mean = w.mean + (v-oldm)/float64(w.n)
// w.sigma = w.sigma + (v-oldm)*(v-w.mean)
// with kahan summation algorithm
w.mean, w.cmean = kahan(w.mean, (v-oldm)/float64(w.n), w.cmean)
w.sigma, w.csigma = kahan(w.sigma, (v-oldm)*(v-w.mean), w.csigma)
}
func kahan(sum, v, c float64) (float64, float64) {
y := v - c
t := sum + y
return t, (t - sum) - y
}