weighted_moving_average.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_
  5. #define CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_
  6. #include <stdint.h>
  7. #include <deque>
  8. #include "chromecast/base/statistics/weighted_mean.h"
  9. namespace chromecast {
  10. // Calculates the weighted moving average of recent points. The points
  11. // do not need to be evenly distributed on the X axis, but the X coordinate
  12. // is assumed to be generally increasing.
  13. //
  14. // Whenever a new sample is added using AddSample(), old samples whose
  15. // x coordinates are farther than |max_x_range_| from the new sample's
  16. // x coordinate will be removed from the average. Note that |max_x_range_|
  17. // must be non-negative.
  18. class WeightedMovingAverage {
  19. public:
  20. explicit WeightedMovingAverage(int64_t max_x_range);
  21. WeightedMovingAverage(const WeightedMovingAverage&) = delete;
  22. WeightedMovingAverage& operator=(const WeightedMovingAverage&) = delete;
  23. ~WeightedMovingAverage();
  24. int64_t max_x_range() const { return max_x_range_; }
  25. // Returns the current number of samples that are in the weighted average.
  26. size_t num_samples() const { return samples_.size(); }
  27. // Adds an (x, y) sample with the provided weight to the average.
  28. // |weight| should be non-negative.
  29. void AddSample(int64_t x, int64_t y, double weight);
  30. // Gets the current average and standard error.
  31. // Returns |true| if the average exists, |false| otherwise. If the average
  32. // does not exist, |average| and |error| are not modified.
  33. bool Average(int64_t* average, double* error) const;
  34. // Clears all current samples from the moving average.
  35. void Clear();
  36. private:
  37. struct Sample {
  38. int64_t x;
  39. int64_t y;
  40. double weight;
  41. };
  42. const int64_t max_x_range_;
  43. std::deque<Sample> samples_;
  44. WeightedMean mean_;
  45. };
  46. } // namespace chromecast
  47. #endif // CHROMECAST_BASE_STATISTICS_WEIGHTED_MOVING_AVERAGE_H_