Moving, Rolling and Running (Average)

rolling and running

Simple Moving Average

A Finite Impulse Response Filter, or Moving Average is an example of a low-pass filter typically used in signal processing. In its most basic form it’s simply used to smooth data. Its true purpose is to smooth out short-term fluctuations and highlight longer-term trends or cycles. When used without any specific connection to time, a moving average filters out the higher frequency components.

//no error checking is performed on exceeding the bounds of data
float SimpleMovingAverage(float data[], int index, int period) {
  float sample;

  sample = 0.0;
  for (i=(index – period + 1); i<=index; i++)
    sample += data[i];
  return (sample/period);

The period selected depends on the type of movement of interest, such as short, intermediate, or long term. If the data is not centered around the mean, a simple moving average lags behind the latest datum point by half the sample width. A Simple Moving Average (SMA) can also be disproportionately influenced by old datum points dropping out or new data coming in.

Exponential Moving Average

An exponential moving average, or exponentially weighted moving average, is a type of impulse response filter that applies weighting factors which decrease exponentially.

float accumulator;
const float alpha = 1.0; //0 to 1

float ExponentialMovingAverage(float new_value) {
  accumulator += alpha*(new_value - accumulator);

In this example, we use an “accumulator” variable, which, as each sample is evaluated is updated with the new value. The function requires a constant “alpha” that is between 0 and 1, where the effect of a given sample only lasts for the requisite period.

Rolling Average Approximation

Finally, you can approximate a rolling average by applying a weighted average on your input stream. This way, you don’t need to maintain a large array of values. However, since it’s an approximation, it’s value will not exactly match a true rolling average.

float sma;
int period;

float ApproximateSimpleMovingAverage(float new_value) {
  sma *= (period – 1);
  sma += vew_value;
  sma /= period;
  return sma;

Basic Comparison

The following chart demonstrates the 3 types of moving averages on a sample data set. The SMA has a period of 7, the exponential average uses an alpha of 0.4, and the approximate-rolling average uses a period of 5.

Moving Average Examples


About Jim Eli

µC experimenter
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s