Skip to content

Instantly share code, notes, and snippets.

@jsmorph
Created April 8, 2019 13:28
Show Gist options
  • Save jsmorph/0592ce9b2cf7bd7810f381a23b4772de to your computer and use it in GitHub Desktop.
Save jsmorph/0592ce9b2cf7bd7810f381a23b4772de to your computer and use it in GitHub Desktop.
Incremental variance
// Package main demos TAOCP, Vol. 2, p. 232 algorithm for incremental variance.
package main
import (
"fmt"
"math/rand"
)
type Var struct {
N int
M, S float64
}
func (v *Var) Add(x float64) {
v.N++
if v.N == 1 {
v.M = x
v.S = 0
}
m := v.M + (x - v.M)/float64(v.N)
v.S += (x - v.M)*(x-m)
v.M = m
}
func (v *Var) Variance() float64 {
switch v.N {
case 0, 1:
return 0
default:
return v.S/float64(v.N-1)
}
}
func main() {
v := &Var{}
for i := 0; i < 10; i++ {
x := rand.Float64()
fmt.Printf("%f ", x)
v.Add(x)
}
fmt.Printf("\nv=%f\n", v.Variance())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment