Skip to content

Instantly share code, notes, and snippets.

@J3698
Created May 7, 2019 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save J3698/8122358691f778532e386b947adf8843 to your computer and use it in GitHub Desktop.
Save J3698/8122358691f778532e386b947adf8843 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include "moving_average.h"
movingAverage_t* movingAverage_new(size_t num_samples) {
movingAverage_t *ma = malloc(sizeof(movingAverage_t));
ma->samples = malloc(num_samples * sizeof(double));
ma->oldest_index = 0;
ma->num_samples = num_samples;
}
void movingAverage_free(movingAverage_t *ma) {
free(ma->samples);
free(ma);
}
void movingAverage_update(movingAverage_t *ma, double new_sample) {
ma->average -= ma->samples[ma->oldest_index];
ma->samples[ma->oldest_index] = new_sample;
ma->average += ma->samples[ma->oldest_index];
ma->oldest_index = (ma->oldest_index + 1) % ma->num_samples;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment