Neither one nor Many

 
July 24 2011

Calculation of average

I had a problem in my project, and came up with this solution. For each pixel on the screen I calculated a bunch of numbers. In a second pass I needed averages of these numbers. So I stored each in a vector and in the second pass calculated averages. Like this:

double result2 = 0;
for (auto i=myNumbers.begin(); i!=myNumbers.end(); ++i) {
    double &Nx = *i;
    result2 += Nx * (1.0 / N);
}
 // result2 now contains the average

The problem is that this method needs to know N inside the loop. So I came up with this:

double result3 = 0;
for (int i=0; i<100; i++) {
    int nmbr = (int)dist(eng);
    cout << ((i == 0) ? "random numbers: " : ", ");
    cout << nmbr;

    // Calculate the average, N is not required, storing all numbers or TOTAL is not required.
    double frac1 = 1.0 / static_cast<double>(i + 1); // 1/1, 1/2, 1/3, 1/4,...
    double frac2 = 1.0 - frac1; // 0, 1/2, 2/3, 3/4,...

    result3 *= frac2;
    result3 += nmbr * frac1;
}
 // result3 now contains the average

Download the source code snippet here.

C++ Comments (0)


Leave a Reply

Comment may not be visible immediately, because I process everything manually.**

**) I plan to automate this.., but it's on my ToDo since for ever..


Author:
Ray Burgemeestre
february 23th, 1984

Topics:
C++, Linux, Webdev

Other interests:
Music, Art, Zen