Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | // 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 | |
| 5 | package llrb |
| 6 | |
| 7 | import "math" |
| 8 | |
| 9 | // avgVar maintains the average and variance of a stream of numbers |
| 10 | // in a space-efficient manner. |
| 11 | type avgVar struct { |
| 12 | count int64 |
| 13 | sum, sumsq float64 |
| 14 | } |
| 15 | |
| 16 | func (av *avgVar) Init() { |
| 17 | av.count = 0 |
| 18 | av.sum = 0.0 |
| 19 | av.sumsq = 0.0 |
| 20 | } |
| 21 | |
| 22 | func (av *avgVar) Add(sample float64) { |
| 23 | av.count++ |
| 24 | av.sum += sample |
| 25 | av.sumsq += sample * sample |
| 26 | } |
| 27 | |
| 28 | func (av *avgVar) GetCount() int64 { return av.count } |
| 29 | |
| 30 | func (av *avgVar) GetAvg() float64 { return av.sum / float64(av.count) } |
| 31 | |
| 32 | func (av *avgVar) GetTotal() float64 { return av.sum } |
| 33 | |
| 34 | func (av *avgVar) GetVar() float64 { |
| 35 | a := av.GetAvg() |
| 36 | return av.sumsq/float64(av.count) - a*a |
| 37 | } |
| 38 | |
| 39 | func (av *avgVar) GetStdDev() float64 { return math.Sqrt(av.GetVar()) } |