From b66e7d624ccd04f48d6473128f31fe799e298f80 Mon Sep 17 00:00:00 2001 From: andig Date: Fri, 13 Aug 2021 15:15:13 +0200 Subject: [PATCH 1/2] Improve SimpleEWMA zero value handling --- ewma.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/ewma.go b/ewma.go index 44d5d53..e1bd35c 100644 --- a/ewma.go +++ b/ewma.go @@ -59,26 +59,30 @@ func NewMovingAverage(age ...float64) MovingAverage { type SimpleEWMA struct { // The current value of the average. After adding with Add(), this is // updated to reflect the average of all values seen thus far. - value float64 + value *float64 } // Add adds a value to the series and updates the moving average. func (e *SimpleEWMA) Add(value float64) { - if e.value == 0 { // this is a proxy for "uninitialized" - e.value = value + if e.value == nil { // this is a proxy for "uninitialized" + e.value = &value } else { - e.value = (value * DECAY) + (e.value * (1 - DECAY)) + *e.value = (value * DECAY) + (*e.value * (1 - DECAY)) } } // Value returns the current value of the moving average. func (e *SimpleEWMA) Value() float64 { - return e.value + if e.value == nil { // this is a proxy for "uninitialized" + return 0 + } else { + return *e.value + } } // Set sets the EWMA's value. func (e *SimpleEWMA) Set(value float64) { - e.value = value + e.value = &value } // VariableEWMA represents the exponentially weighted moving average of a series of From dd51f37c1ade5b3c07828c2f3e536240dd4f2148 Mon Sep 17 00:00:00 2001 From: andig Date: Sat, 14 Aug 2021 13:56:32 +0200 Subject: [PATCH 2/2] Update ewma.go --- ewma.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ewma.go b/ewma.go index e1bd35c..2412f16 100644 --- a/ewma.go +++ b/ewma.go @@ -67,7 +67,7 @@ func (e *SimpleEWMA) Add(value float64) { if e.value == nil { // this is a proxy for "uninitialized" e.value = &value } else { - *e.value = (value * DECAY) + (*e.value * (1 - DECAY)) + *e.value = (value * DECAY) + (e.Value() * (1 - DECAY)) } }