Last active
July 10, 2022 11:35
-
-
Save manju4ever/aa4bd9a2f779b932402b173203dc24a0 to your computer and use it in GitHub Desktop.
Wellford 1 pass method of calculating variance in Go
This file contains hidden or 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 | |
import ( | |
"fmt" | |
"math" | |
) | |
func main() { | |
// Find the definition after main | |
tracker := WellfordVariance{} | |
samples := []float64{ | |
1.1, 9.1, 2.33, 3.21, -2.3, 1.001, 0.01, | |
3.45, 2.28, 4.1, 8.94, 2.1, 3.33, 4.2, 3.2} | |
fmt.Println("Sample Data = ", samples) | |
// Keep adding elements dynamically | |
for _, val := range samples { | |
tracker.Add(val) | |
if tracker.Deviation() > tracker.M { | |
fmt.Printf( | |
"\n/!\\ High Deviation Detected - Val = %f, S = %f\n", | |
val, tracker.Deviation()) | |
} | |
} | |
fmt.Println("\n-- FINISHED") | |
fmt.Println("-- Total Samples = ", tracker.count) | |
fmt.Printf("-- Mean = %f, Variance = %f, Deviation = %f", | |
tracker.Mean(), | |
tracker.Variance(), | |
tracker.Deviation()) | |
} | |
/* -- Wellford Variance -- */ | |
// WellfordVariance - struct to keep track of things dynamically | |
type WellfordVariance struct { | |
count int | |
M, S float64 | |
} | |
//Add - Dynamic Addition of Values and Keeping Track of Mean & Numerator | |
func (wv *WellfordVariance) Add(x float64) { | |
wv.count = wv.count + 1 | |
oldM := wv.M | |
wv.M += (x - wv.M) / (float64(wv.count)) | |
wv.S = (x - wv.M) * (x - oldM) | |
} | |
// Variance - Return the Variance as of Now ! | |
func (wv *WellfordVariance) Variance() float64 { | |
return wv.S | |
} | |
// Deviation - Return the Std Deviation as of Now ! | |
func (wv *WellfordVariance) Deviation() float64 { | |
return math.Sqrt(wv.S) | |
} | |
// Mean - Return the Mean as of Now ! | |
func (wv *WellfordVariance) Mean() float64 { | |
return wv.M | |
} | |
// Count - Return the count of elements scanned as of Now ! | |
func (wv *WellfordVariance) Count() int { | |
return wv.count | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment