weighted_mean.cc 956 B

1234567891011121314151617181920212223242526272829303132333435
  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_mean.h"
  5. #include <cmath>
  6. namespace chromecast {
  7. WeightedMean::WeightedMean() = default;
  8. void WeightedMean::Reset() {
  9. weighted_mean_ = 0.0;
  10. variance_sum_ = 0.0;
  11. sum_weights_ = 0.0;
  12. sum_squared_weights_ = 0.0;
  13. }
  14. void WeightedMean::AddDelta(double delta, double weight) {
  15. double old_sum_weights = sum_weights_;
  16. sum_weights_ += weight;
  17. // Use std::abs() to handle negative weights (ie, removing a sample).
  18. sum_squared_weights_ += weight * std::abs(weight);
  19. if (sum_weights_ == 0) {
  20. weighted_mean_ = 0;
  21. variance_sum_ = 0;
  22. } else {
  23. double mean_change = delta * weight / sum_weights_;
  24. weighted_mean_ += mean_change;
  25. variance_sum_ += old_sum_weights * delta * mean_change;
  26. }
  27. }
  28. } // namespace chromecast