Created
December 25, 2017 13:18
-
-
Save yuri-tikhomirov/3171b4ff6ef9dc2cf92e81e24299e992 to your computer and use it in GitHub Desktop.
Incremental mean counter
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
// | |
// IncrementalMeanCounter used to count average value in streaming mode | |
// (when it is impossible to accumulate values in a collection to compute after). | |
// | |
// (c) 2017 Yuri Tikhomirov @ ModumLab | |
// | |
public struct IncrementalMeanCounter | |
{ | |
double mean, count; | |
public static IncrementalMeanCounter Empty { | |
get { | |
return new IncrementalMeanCounter(); | |
} | |
} | |
public void Reset() | |
{ | |
mean = count = 0.0; | |
} | |
public void AddValue(double val) | |
{ | |
count += 1.0; | |
mean = mean + ((val - mean) / count); | |
} | |
public double Mean { get { return mean; } } | |
public static implicit operator double(IncrementalMeanCounter imc) | |
{ | |
return imc.mean; | |
} | |
public static IncrementalMeanCounter operator + (IncrementalMeanCounter imc, double val) | |
{ | |
var count = imc.count + 1.0; | |
return new IncrementalMeanCounter() { | |
count = count, | |
mean = imc.mean + ((val - imc.mean) / count) | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment