Skip to content

Instantly share code, notes, and snippets.

@patrickelectric
Last active January 8, 2020 19:11
Show Gist options
  • Save patrickelectric/d85f68dca9ae1a021634e6c8f9843985 to your computer and use it in GitHub Desktop.
Save patrickelectric/d85f68dca9ae1a021634e6c8f9843985 to your computer and use it in GitHub Desktop.
moving average filter
/**
* @brief Helper struct to do a moving average
* Ref: https://en.wikipedia.org/wiki/Moving_average
*
* @tparam T
*/
template <typename T> struct MovingAverage {
/**
* @brief Update average
*
* @param newValue
*/
void update(T newValue)
{
n++;
average += (newValue - average) / static_cast<float>(n);
}
/**
* @brief Reset average
*
*/
void reset()
{
n = 0;
average = {};
}
/**
* @brief Return the moving average result
*
* @return T
*/
T result() { return average; }
private:
T average = {};
uint n = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment