Moving averages are useful since they do not require a buffer of samples to be maintained. Here is a simple implementation in C:
#include <stdio.h>
float ave(float num)
{
static float fAve = 0.0f;
static unsigned int fSmp = 0;
float weight = 0.0f;
fSmp++;
weight = 1.0f / fSmp;
fAve = (weight * num) + ((1 - weight) * fAve);
return(fAve);
}
int main(int argc, const char *argv[])
{
char str[100] = {0};
float num = 0;
/* Run until user enters invalid number. */
for(;;)
{
fputs("Enter number: ", stdout);
fflush(stdout);
if(fgets(str, sizeof(str), stdin))
{
if(1 == sscanf(str, "%f", &num))
printf(" average = %f\r\n", ave(num));
else
break;
}
}
return(0);
}
Example output:
Enter number: 1.23
average = 1.230000
Enter number: -4.56
average = -1.665000
Enter number: q