Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yuri-tikhomirov
Created December 25, 2017 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuri-tikhomirov/3171b4ff6ef9dc2cf92e81e24299e992 to your computer and use it in GitHub Desktop.
Save yuri-tikhomirov/3171b4ff6ef9dc2cf92e81e24299e992 to your computer and use it in GitHub Desktop.
Incremental mean counter
//
// 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