Search code examples
c++loopsstandardsdeviation

Standard Deviation Program with While Loop cpp / c++


Hello everyone I am required to create a program that reads in an input file containing digits and then finds the standard deviation using the following method:

sqrt(( x1 - mu )^2 + ( x2 - mu )^2 + ( x3 - mu )^2 + ( x4 - mu )^2)/mu

The x's are equal to the digits read in, and mu is equal to the mean. I am having trouble doing this because I don't know how to set up different variables (x1, x2, x3, x4) for the values that are read in from the input file within my while loop. Also it is important to note that we are supposed to read in the first digit and then every third digit after that. This is what I have so far:

    fin.open(FileName.c_str());
    if (fin.fail())
    {
        cout <<"Bad file name or location.\n" ;
        exit(0);
    }
    fin >> X;
    first_score = X;
    Counter = 0, Sum=0;
    while (!fin.eof() )
    {   
        Counter++;
        if (Counter%3==0)
        {
            fin >> X;
            Sum += X;
            Counter++;
            Counter2 ++ ;
            Avg = (Sum+first_score)/(Counter2+1);
            deviation = pow((X-Avg),2);
            sum_of_deviations += deviation;
        }
        fin >> Score;
    }
    quotient_of_deviations = sum_of_deviations/Counter2;
    standard_dev2 = sqrt(quotient_of_deviations);
    fin.close();

I know this code is logically incorrect because I am subtracting a different mean from every x value. Does someone know how I could assign the X within the while loop to a new variable each time the while loop is ran? If I can do this, I will then be able to subtract each x value by the same mean outside of the loop. I hope I explained that good enough so that you guys can understand my problem. If not I will be happy to explain more. Thanks in advance for your time.


Solution

  • If you don't want to use arrays then you might have to read file multiple times.

    int counter = 0;
    int sum1=0;
    ifstream fin,fin2;   //fin and fin2 to read the file each time.
    fin.open("myfile.txt");  //opening a file to read it.
    
    
    
    while (!fin.eof() )   //reading a file
    {
       fin>>X;
       sum1  = sum1+X;    //adding all the numbers in the file
       counter++;      //counting number of items in the file
    
    }
    
    fin.close()
    //Now first calculate mean
    int mean=0;
    mean = sum1/counter;   //calculating the mean
    
    //now calculate sum of squares of difference of each term and mean
    int sum2=0;
    fin2.open("myfile.txt");     //again opening the file with fin2
    
    while (!fin2.eof() )   //again reading the file
    {
       fin2>>Y;
       sum2  = sum2+ pow(Y-mean,2);     
    
    }
    
    fin2.close()
    
    
     //finally standard deviation
    
     double sd=0;
    
     sd = sqrt(sum2/mean);    //calculating standard deviation