Average Values

03 Nov 2009 . Edited: 03 Nov 2009

Hi,

I noticed a number of people talking about averages, and in particular, averaging to overcome spurious signals. I thought it might be worth discussing some theory and providing some code examples to help in this area.

If you have a number of samples and you want to take an average, it is worth thinking about what you are trying to achieve by taking an average. In the case that some of these samples are spurious, taking the mean average will certainly dilute the impact of these values, but won't remove them. More appropriate would be the median average, which will naturally ignore outliers.

For anyone that needs a reminder of the differences:

Arithmetic Mean

The sum of all the samples, divided by the number of samples

Median

The middle sample when the samples are placed in order

So, lets get to some code examples:

To calculate the mean, we can simply add up all the values in an array of samples, and return the average by dividing by the number of samples:

float mean(float *samples, int n) {
    float sum = 0.0;
    for (int i=0; i<n; i++) {
        sum += samples[i];
    }
    return sum / (float)n;
}

For the median implementation I've used the C qsort function to sort the list in to order, then simply return the middle sample. The compare function is needed to tell qsort how to sort values:

int compare(const void *a, const void *b) {
    return (int)(*(float*)a - *(float*)b);
}

float median(float *samples, int n) {
    qsort(samples, n, sizeof(float), compare);
    return samples[(n - 1)/2];
}

Note that this only deals with an odd number of samples to keep the example simple. The code in the program example below includes logic to handle even numbers of samples too, and a simple test program to sample an AnalogIn and print out the averages.

Hope this is useful!

05 Mar 2010

Programmers might also consider using a moving average or an FIR filter to process the information.  An FIR routine uses multiply-accumulate operations, so no heavy-duty math is involved.  Iowegian International have a nice FIR-filter-design software package, "ScopeFIR 5" that developers can use for free for 60 days.  Price is $199, which seems reasonable, given the time involved in working through the coefficients needed for an FIR filter.  I have used the software--which has several graphical windows of filter response--and it works well.  Visit www.dspguru.com/dsp.  I have no relationship to this company and offer the info just to help others. --Jon Titus

05 Mar 2010 . Edited: 05 Mar 2010

or a simple 1st order IIR filter.

Such as:

 

 

typdef struct
{
    int32_t prev;
    uint16_t gain;
}IIR_Filter_Data;

int16_t IIR_Filter(int16_t input, IIR_Filter_Data* Fdata)
{
    Fdata->prev += input * Fdata->gain;

    return (Fdata->prev >> 16);
}

Doesn't cost you $200 either.