Display an updated average of random numbers in a file

147 views Asked by At

I have a program that displays one random number in file .

#include <iostream>
#include <fstream>
#include <random>


using namespace std;

int main() {

    std::ofstream file("file.txt",std::ios_base::app);

    int var = rand() % 100 + 1; 

        file<<var ;


        return 0;

}

Results after 4 trial :

1,2 2,20 3,40 1,88 

I am looking to not display the numbers . but only there updated average after each try. Is there any way to calculate the average incrementally ?

Inside the file should exist only the average value :

For example first trial :

1.2

second trial displays the average in the file (1.2+2.2)/2

1.7
3

There are 3 answers

0
Pandrei On BEST ANSWER

Even though it's kind of strange, what you are trying to do, and I'm sure there is a better way of doing it, here's how you can do it:

float onTheFlyAverage()
{
   static int nCount=0;
   float avg, newAvg;

   int newNumber = getRandomNum();
   nCount++; //increment the total number count
   avg = readLastAvgFromFile(); //this will read the last average in your file
   newAvg = avg*(nCount-1)/nCount+ (float)(newNumber)/nCount;

   return newAvg;
}

If for some reason you want to keep an average in a file which you provide as input to your program and expect it to keep on averaging numbers for you (a sort of stop and continue feature), you will have to save/load the total number count in the file as well as the average.

But if you do it in one go this should work. IMHO this is far from the best way of doing it - but there you have it :)

NOTE: there is a divide by 0 corner-case I did not take care of; I leave that up to you.

0
Denis On

You can use some simple math to calculate the mean values incrementally. However you have to count how many values contribute to the mean.

Let's say you have n numbers with a mean value of m. Your next number x contributes to the mean in the following way:

m = (mn + x)/(n+1)

4
Nick Volynkin On

It's bad for performance to divide and then multiply the average back. I suggest you store the sum and number.

(pseudocode)
// these variables are stored between function calls
int sum
int n

function float getNextRandomAverage() {
    int rnd = getOneRandom()
    n++;
    sum += rnd;
    float avg = sum/n
    return avg
}

function writeNextRandomAverage() {
    writeToFile(getNextRandomAverage())
}

Also it seems strange to me that your method closes the file. How does it know that it should close it? What if the file should be used later? (Say, consecutive uses of this method).