Created
April 8, 2019 13:28
-
-
Save jsmorph/0592ce9b2cf7bd7810f381a23b4772de to your computer and use it in GitHub Desktop.
Incremental variance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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