weighted_moving_average.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. #include "chromecast/base/statistics/weighted_moving_average.h"
  5. #include <math.h>
  6. #include "base/check_op.h"
  7. namespace chromecast {
  8. WeightedMovingAverage::WeightedMovingAverage(int64_t max_x_range)
  9. : max_x_range_(max_x_range) {
  10. DCHECK_GE(max_x_range_, 0);
  11. }
  12. WeightedMovingAverage::~WeightedMovingAverage() {}
  13. void WeightedMovingAverage::AddSample(int64_t x, int64_t y, double weight) {
  14. DCHECK_GE(weight, 0);
  15. if (!samples_.empty())
  16. DCHECK_GE(x, samples_.back().x);
  17. Sample sample = {x, y, weight};
  18. samples_.push_back(sample);
  19. mean_.AddSample(y, weight);
  20. // Remove old samples.
  21. while (x - samples_.front().x > max_x_range_) {
  22. const Sample& old_sample = samples_.front();
  23. mean_.AddSample(old_sample.y, -old_sample.weight);
  24. samples_.pop_front();
  25. }
  26. DCHECK(!samples_.empty());
  27. }
  28. bool WeightedMovingAverage::Average(int64_t* average, double* error) const {
  29. if (samples_.empty() || mean_.sum_weights() == 0)
  30. return false;
  31. *average = static_cast<int64_t>(round(mean_.weighted_mean()));
  32. const double effective_sample_size =
  33. mean_.sum_weights() * mean_.sum_weights() / mean_.sum_squared_weights();
  34. const double variance = mean_.variance_sum() / mean_.sum_weights();
  35. *error = sqrt(variance / effective_sample_size);
  36. return true;
  37. }
  38. void WeightedMovingAverage::Clear() {
  39. samples_.clear();
  40. mean_ = WeightedMean();
  41. }
  42. } // namespace chromecast