
A very simple and very easy to implement software filter is a first-order low-pass filter. This is similar to an electrical RC filter. The algorithm is very easy:
On = C In + (1 – C) On-1
Where I in an array if input data, O is the output, and C is the filter coefficient with a value between 0 and 1.
It is simple to see what this algorithm does. The new output is based on the latest input, and the previous output value. The amount of change the new value has is determined by the filter coefficient. The larger the filter coefficient (i.e. the closer to a value of 1) the more effect the newest input has and the higher the frequencies allowed to pass. The lower the coefficient, the larger the previous output value and the more high frequencies are attenuated.
Here is a little demo do show how the filter works:
The demo consists of two sine waves and some Gaussian noise. The red line represents the true sine wave. The blue represents the sine wave with the Gaussian noise added in. The green line is the filtered signal.
Try adjusting the amount of noise and the filter coefficient. This will demonstrate how the filter copes with various amounts of noise. The closer the green line is to the red line, the better job the filter has done.
There are a couple of items that are fairly apparent from this demo. The lower the filter coefficient the less noise gets through, but the more the filtered signal is attenuated and phase-shifted. That is, the peak values of the green line are not as high as the red line (attenuation), and the green line mimics the shape of the red line to the more and more to the right (phase-shift).
The attenuation and phase-shift will be based on the filter coefficient as well as the frequency of the incoming signal. The lower the frequency, the less attenuation and phase-shift. This is easy to see by setting the amplitude of the second sine wave to 0, and adjusting the frequency of the first sine wave with a constant filter coefficient. The attenuation is precisely what a low-pass filter is designed to do—allow only the lower frequencies to pass while blocking, or at least limited the higher frequencies.
This kind of filter has limited uses in software. It is a fairly weak filter and implementing a rolling-average often achieves better results. I had written back in 2006 about how I replaced this filter with a custom low-pass filter using an FFT. I haven't use this filter in any applications since, but it was interesting looking back on it.