weighted_mean.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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_MEAN_H_
  5. #define CHROMECAST_BASE_STATISTICS_WEIGHTED_MEAN_H_
  6. #include <stdint.h>
  7. namespace chromecast {
  8. // Calculates the weighted mean (and variance) of a set of values. Values can be
  9. // added to or removed from the mean.
  10. class WeightedMean {
  11. public:
  12. WeightedMean();
  13. double weighted_mean() const { return weighted_mean_; }
  14. // The weighted variance should be calculated as variance_sum()/sum_weights().
  15. double variance_sum() const { return variance_sum_; }
  16. double sum_weights() const { return sum_weights_; }
  17. double sum_squared_weights() const { return sum_squared_weights_; }
  18. // Adds |value| to the mean if |weight| is positive. Removes |value| from
  19. // the mean if |weight| is negative. Has no effect if |weight| is 0.
  20. template <typename T>
  21. void AddSample(T value, double weight) {
  22. AddDelta(value - weighted_mean_, weight);
  23. }
  24. // Resets to initial state.
  25. void Reset();
  26. private:
  27. void AddDelta(double delta, double weight);
  28. double weighted_mean_ = 0.0;
  29. double variance_sum_ = 0.0;
  30. double sum_weights_ = 0.0;
  31. double sum_squared_weights_ = 0.0;
  32. };
  33. } // namespace chromecast
  34. #endif // CHROMECAST_BASE_STATISTICS_WEIGHTED_MEAN_H_