a go package that implements the efficient, accurate, and stable calculation of online statistical quantities.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
945B

  1. package ostat
  2. import (
  3. "errors"
  4. "math"
  5. )
  6. // from http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
  7. type OnlineStat struct {
  8. n int64
  9. mean float64
  10. m2 float64
  11. Max float64
  12. Min float64
  13. }
  14. func NewOnlineStat() *OnlineStat {
  15. return &OnlineStat{
  16. Min: math.Inf(1),
  17. Max: math.Inf(-1),
  18. }
  19. }
  20. func (os *OnlineStat) Push(v float64) {
  21. os.n += 1
  22. if v < os.Min {
  23. os.Min = v
  24. }
  25. if v > os.Max {
  26. os.Max = v
  27. }
  28. delta := v - os.mean
  29. os.mean = os.mean + delta/float64(os.n)
  30. os.m2 = os.m2 + delta*(v-os.mean)
  31. }
  32. func (os *OnlineStat) Mean() (float64, error) {
  33. if os.n == 0 {
  34. return 0.0, errors.New("no data")
  35. }
  36. return os.mean, nil
  37. }
  38. func (os *OnlineStat) Variance() (float64, error) {
  39. if os.n == 0 {
  40. return 0.0, errors.New("no data")
  41. }
  42. return os.m2 / float64(os.n-1), nil
  43. }
  44. func (os *OnlineStat) StdDev() (float64, error) {
  45. variance, err := os.Variance()
  46. return math.Sqrt(variance), err
  47. }