954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

need a little help with standard deviation

Hello I am new to C++, I have this program which i take an input file and i have to find the average and standard deviation of the numbers in the file. I have part of the program completed but i don't know where to go from there. can someone please help me?

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cmath>

int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;

in_stream.open("infile.txt");
if(in_stream.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}

outstream.open("outfile.txt");
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}

double next,sum = 0;
double average;
double s_dev = 0;
int count = 0;
while(in_stream >> next)
{
sum = sum + next;
count++;
}
average = sum/count;
jazzyjoe
Newbie Poster
1 post since Jul 2005
Reputation Points: 10
Solved Threads: 0
 
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

You seem to have computed the average correctly. The most efficient way to compute the standard deviation is to use the formula

st. dev. = sqrt( (sum of squares -ct*square of av)/(ct - 1) )

so what you need to do is have another variable, say sum2, which, like sum, starts out at 0 and in the while loop is incremented by the formula sum2 = sum2 + next*next. The the st dev is given by

stdev = sqrt( (sum2-ct*average*average)/(ct-1) )
murschech
Junior Poster in Training
60 posts since Dec 2004
Reputation Points: 21
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You