-
Notifications
You must be signed in to change notification settings - Fork 2
/
stats.go
79 lines (68 loc) · 1.13 KB
/
stats.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package stats
import (
"math"
)
func NewStats() *Stats {
return &Stats{
max: -math.MaxFloat64,
min: math.MaxFloat64,
variance: [2]float64{-1, 0},
}
}
type Stats struct {
count int64
sum, min, max float64
variance [2]float64
}
func (s *Stats) Count() int64 {
return s.count
}
func (s *Stats) Sum() float64 {
return s.sum
}
func (s *Stats) Mean() float64 {
if s.count == 0 {
return 0
}
return s.sum / float64(s.count)
}
func (s *Stats) Min() float64 {
if s.count == 0 {
return 0
}
return s.min
}
func (s *Stats) Max() float64 {
if s.count == 0 {
return 0
}
return s.max
}
func (s *Stats) StdDev() float64 {
return math.Sqrt(s.Variance())
}
func (s *Stats) Variance() float64 {
if s.count <= 1 {
return 0
}
return s.variance[1] / float64(s.count-1)
}
func (s *Stats) Update(v float64) {
s.count++
s.sum += v
if v < s.min {
s.min = v
}
if v > s.max {
s.max = v
}
if s.variance[0] == -1 {
s.variance[0] = v
s.variance[1] = 0.0
} else {
v0 := s.variance[0]
v1 := s.variance[1]
s.variance[0] = v0 + (v-v0)/float64(s.count)
s.variance[1] = v1 + (v-v0)*(v-s.variance[0])
}
}