@@ -5,16 +5,18 @@ import (
5
5
"sync"
6
6
)
7
7
8
+ // SimpleMovingVariance implements a simple moving variance calculation based on the simple moving average.
8
9
type SimpleMovingVariance struct {
9
10
average * SimpleExponentialMovingAverage
10
11
variance * SimpleExponentialMovingAverage
11
12
12
13
stdev float64 // square root of the estimated variance
13
- normalized float64 // (signal - mean) / stdev
14
+ normalized float64 // (input - mean) / stdev
14
15
15
16
mu sync.RWMutex
16
17
}
17
18
19
+ // NewSimpleMovingVariance will create a new exponential moving variance approximation based on the SimpleMovingAverage
18
20
func NewSimpleMovingVariance (
19
21
alphaAverage float64 ,
20
22
alphaVariance float64 ,
@@ -33,6 +35,8 @@ func NewSimpleMovingVariance(
33
35
}, nil
34
36
}
35
37
38
+ // Add a single sample and update the internal state.
39
+ // returns true if the internal state was updated, also return the current value.
36
40
func (m * SimpleMovingVariance ) Add (value float64 ) (float64 , bool ) {
37
41
m .mu .Lock ()
38
42
defer m .mu .Unlock ()
@@ -50,7 +54,7 @@ func (m *SimpleMovingVariance) Add(value float64) (float64, bool) {
50
54
// edge case
51
55
normalized = (value - mean ) / stdev
52
56
}
53
- //fmt.Printf("\tMV add: value=%0.5f mean=%0.5f variance=%0.5f stdev=%0.5f normalized=%0.5f\n", value, mean, variance, stdev, normalized)
57
+
54
58
if stdev != m .stdev || normalized != m .normalized {
55
59
changed = true
56
60
}
@@ -59,12 +63,14 @@ func (m *SimpleMovingVariance) Add(value float64) (float64, bool) {
59
63
return stdev , changed
60
64
}
61
65
66
+ // Get the current value.
62
67
func (m * SimpleMovingVariance ) Get () float64 {
63
68
m .mu .RLock ()
64
69
defer m .mu .RUnlock ()
65
70
return m .variance .Get ()
66
71
}
67
72
73
+ // Reset the internal state as if no samples were ever added.
68
74
func (m * SimpleMovingVariance ) Reset () {
69
75
m .mu .Lock ()
70
76
m .average .Reset ()
@@ -74,6 +80,7 @@ func (m *SimpleMovingVariance) Reset() {
74
80
m .mu .Unlock ()
75
81
}
76
82
83
+ // Update will update the value given an operation function
77
84
func (m * SimpleMovingVariance ) Update (operation func (value float64 ) float64 ) {
78
85
m .mu .Lock ()
79
86
defer m .mu .Unlock ()
0 commit comments