Posts Tagged ‘running average’

Weighted Average Class

December 22, 2010 Leave a comment

Continuing on my current fascination with math and code to implement it, I decided to write a class for weighted average monitoring.  Creating a running average of a stream of numbers can be complicated, and consume many variables (depending on how many samples make up the average).  It also means you have create some sort of queue so the values can shift such that the n most current samples are available for calculation.  That can be a lot of work.

Average = SUM(nSamples)/n 

I found a shortcut to all of that where an average value is maintained in the background, and a weighted percentage is applied to the newest input value and the previous average.  I am sure this method is not as accurate as averaging the last n values, but the goal is not so much precision, but reducing spikes and anomalies.  In other words, I don’t care what the actual average is; I care that the trend of values over time reduces the spikes and provides usable information to the robot with less error.

Weighted Average = New Sample * %wt + (1-%wt)*Previous Average

This class can help filter sensor data to a robot, making it react more slowly to large value changes.  Try it and let me know what you think…

You can download the code here: WeightedAverage.c