Skip to content

Instantly share code, notes, and snippets.

@spaceMan00
Last active June 22, 2022 09:10
Show Gist options
  • Save spaceMan00/403f759d39a242b6f4c305be0e9d58c0 to your computer and use it in GitHub Desktop.
Save spaceMan00/403f759d39a242b6f4c305be0e9d58c0 to your computer and use it in GitHub Desktop.
A simple moving average implementation in C using a struct object
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct moving_average
{
float *buffer;
int length;
float sum;
int pos;
bool is_filled;
}moving_average_t;
float moving_average_fct(moving_average_t * av_obj, float new_element)
{
//Subtract the oldest number from the prev sum, add the new number
av_obj->sum = av_obj->sum - av_obj->buffer[av_obj->pos] + new_element;
//Assign the nextNum to the position in the array
av_obj->buffer[av_obj->pos] = new_element;
//Increment position internaly
av_obj->pos++;
if (av_obj->pos >= av_obj->length){
av_obj->pos = 0;
av_obj->is_filled = true;
}
//return the average
return av_obj->sum / (float)(av_obj->is_filled ? av_obj->length:av_obj->pos);
}
moving_average_t * alloc_moving_average_obj(int len)
{
moving_average_t * av_obj = malloc(sizeof(moving_average_t));
av_obj->sum = 0;
av_obj->pos = 0;
av_obj->length = len;
av_obj->is_filled = false;
av_obj->buffer = calloc(len, sizeof(float));
return av_obj;
}
void free_moving_average_obj(moving_average_t * av_obj)
{
free(av_obj->buffer);
av_obj->buffer = NULL;
free(av_obj);
}
int main()
{
// a sample array of numbers. The represent "readings" from a sensor over time
int sample[] = {50, 10, 20, 18, 20, 100, 18, 10, 13, 500, 50, 40, 10};
// the size of this array represents how many numbers will be used
// to calculate the average
float average_value = 0;
int count = sizeof(sample) / sizeof(int);
moving_average_t * sensor_av = alloc_moving_average_obj(5);
for(int i = 0; i < count; i++){
average_value = moving_average_fct(sensor_av, sample[i]);
printf("The new average is %2.2f\n", average_value);
}
free_moving_average_obj(sensor_av);
sensor_av = NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment