Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cocowalla/bd6fd0e9c613c0aa9a28c0716a8efb73 to your computer and use it in GitHub Desktop.
Save cocowalla/bd6fd0e9c613c0aa9a28c0716a8efb73 to your computer and use it in GitHub Desktop.
Exponential Weighted Moving Average
public class ExponentialWeightedMovingAverage
{
private bool isInitialized;
// Smoothing/damping coefficient
private double alpha;
public double Average { get; private set; }
public ExponentialWeightedMovingAverage(int samplesPerWindow)
{
// Both `2 / (n + 1)` is a fairly standard ways of choosing an alpha value, even if somewhat arbitrary
this.alpha = 2d / (samplesPerWindow + 1);
}
public double Update(double val)
{
// First tick will initialize the average, subsequent ticks trigger the recursive weighting function
if (this.isInitialized)
{
// EMA[current] = EMA[previous] + alpha * (current_value - EMA[previous])
this.Average += this.alpha * (val - this.Average);
}
else
{
// For the first update, just use the value as-is
this.Average = val;
this.isInitialized = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment