-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage.go
51 lines (41 loc) · 1.2 KB
/
average.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
package counter
import (
"errors"
"fmt"
)
// NewAverage initializes a new Average by setting private values.
// This function is intended for instantiating an Average using data
// from an outside data store.
//
// Note that new(Average) is equivalent to NewAverage(0, 0).
func NewAverage(value float64, count int) *Average {
return &Average{
value: value,
count: count,
}
}
// Average represents an action's cumulative average.
type Average struct {
count int
value float64
}
// Add adds a new value to the cumulative average.
func (a *Average) Add(newVal float64) error {
if newVal <= 0 {
return fmt.Errorf("Average.Add called with non-positive value %f", newVal)
}
if a.count+1 < 0 {
return errors.New("Average.count overflow - cannot add to this Average")
}
newCount := float64(a.count + 1)
largerRatio := (newCount - 1) / newCount
smallerRatio := float64(1) / newCount
newAverage := largerRatio*a.value + smallerRatio*newVal
a.value = newAverage
a.count++
return nil
}
// Count returns the number of data points in the calculated average.
func (a *Average) Count() int { return a.count }
// Value returns the calculated average value.
func (a *Average) Value() float64 { return a.value }