ChunMinChang
12/22/2017 - 3:57 AM

Calculating average without sum

Calculating average without sum #Math

// $ g++ avg.cpp --std=c++11
#include <iostream>

// double average = 0;
// uint64_t count = 0;
// void Add(uint64_t data)
// {
//   average += (data - average) / ++count;
// }

// double GetAverage()
// {
//   return average;
// }

// double UpdateAverage(uint64_t data)
// {
//   static double average = 0;
//   static uint64_t count = 0;
//   average += (data - average) / ++count;
//   return average;
// }

class Averager
{
public:
  Averager()
    : average(0)
    , count(0)
  {}

  ~Averager() {};

  void Add(uint64_t data) { average += (data - average) / ++count; }

  double GetAverage() { return average; }

private:
  double average;
  uint64_t count;
};

int main()
{
  uint64_t data[] = { 23, 14, 75, 23, 66, 78, 11, 26 };

  // for (unsigned int i = 0 ; i < sizeof(data)/sizeof(data[0]) ; ++i ) {
  //   Add(data[i]);
  // }
  // std::cout << "avg: " << GetAverage() << std::endl;

  // double avg;
  // for (unsigned int i = 0 ; i < sizeof(data)/sizeof(data[0]) ; ++i ) {
  //   avg = UpdateAverage(data[i]);
  // }
  // std::cout << "avg: " << avg << std::endl;

  Averager averager;
  for (auto d: data) { // C++ 11 style.
    averager.Add(d);
  }
  std::cout << "avg: " << averager.GetAverage() << std::endl;
}