blob: 2d7e2a3262d2f6741c8de0a634a62d0b2868fa5f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001// Copyright 2010 Petar Maymounkov. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package llrb
6
7import "math"
8
9// avgVar maintains the average and variance of a stream of numbers
10// in a space-efficient manner.
11type avgVar struct {
12 count int64
13 sum, sumsq float64
14}
15
16func (av *avgVar) Init() {
17 av.count = 0
18 av.sum = 0.0
19 av.sumsq = 0.0
20}
21
22func (av *avgVar) Add(sample float64) {
23 av.count++
24 av.sum += sample
25 av.sumsq += sample * sample
26}
27
28func (av *avgVar) GetCount() int64 { return av.count }
29
30func (av *avgVar) GetAvg() float64 { return av.sum / float64(av.count) }
31
32func (av *avgVar) GetTotal() float64 { return av.sum }
33
34func (av *avgVar) GetVar() float64 {
35 a := av.GetAvg()
36 return av.sumsq/float64(av.count) - a*a
37}
38
39func (av *avgVar) GetStdDev() float64 { return math.Sqrt(av.GetVar()) }