Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetMean

 

GetMean is a math code snippet to calculate the mean value of a container.

 

#include <numeric>
#include <vector>

//From htpp://www.richelbilderbeek.nl/CppGetMean.htm
double GetMean(const std::vector<double>& v)
{
  return std::accumulate(v.begin(),v.end(),0.0) / static_cast<double>(v.size());
}

 

 

 

 

 

GetMean test

 

#include <cstdlib>

//From htpp://www.richelbilderbeek.nl/CppGetRandomUniform.htm
double GetRandomUniform()
{
  return static_cast<double>(std::rand())/static_cast<double>(RAND_MAX);
}

#include <numeric>
#include <vector>

//From htpp://www.richelbilderbeek.nl/CppGetMean.htm
double GetMean(const std::vector<double>& v)
{
  return std::accumulate(v.begin(),v.end(),0.0) / static_cast<double>(v.size());
}

#include <iostream>

//From htpp://www.richelbilderbeek.nl/CppGetMean.htm
int main()
{
  std::vector<double> v;

  int max = 1;
  while (max != 33554432)
  {
    for (int i=0; i!=max; ++i)
    {
      v.push_back(GetRandomUniform());
    }
    std::cout << max << ": " << GetMean(v) << std::endl;

    max*=2;
  }
}

 

Screen output:

 

Starting /MyFolder/MyProject...
1: 0.840188
2: 0.672557
4: 0.608647
8: 0.586479
16: 0.501351
32: 0.513881
64: 0.540336
128: 0.522455
256: 0.50905
512: 0.506968
1024: 0.501297
2048: 0.500375
4096: 0.499167
8192: 0.497042
16384: 0.498369
32768: 0.499101
65536: 0.499806
131072: 0.500009
262144: 0.50013
524288: 0.499998
1048576: 0.499937
2097152: 0.500009
4194304: 0.50003
8388608: 0.500028
16777216: 0.500002
/MyFolder/MyProject exited with code 0

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict