The standard deviation calculation on this program doesn't seem to yield an accurate result. Someone please spot the logic error here. Also maybe help neaten this up. Feels like i have too many variables going on here
#include <iostream>
#include <iomanip>
#include <fstream>
#include <math.h>
usingnamespace std;
// program that calculates the standard deviation from a set of numbers on a text file.
//To calculate the standard deviation:
//1. calculate the average or mean
//2. For each number subtract the mean and square the result.
//3. work out the mean of those squared differences
//4. Take the square root of result in 3 above.
int main ()
{
double input [100];
int x = 0;
double average , sum = 0 ;
double deviation = 0 , mean , result;
fstream textfile;
textfile.open("numbers.txt");
while ( !textfile.eof ())
{
textfile >> input [x];
cout << input[x] << endl;
sum = sum + input [x];
average = sum / 10;
// For each number subtract the mean and square the result.
deviation = deviation + ((input [x] - average ) * (input [x] - average )) ;
// work out the mean of those squared differences
mean = (deviation / 10);
// Take the square root of result in above to get standard deviation.
result = sqrt (mean);
x++;
}
cout << " The average of the numbers is: " << average << endl;
cout << " The standard deviation of the numbers is: " << result << endl;
textfile.close();
return 0;
}
Read the numbers with while (textfile >> input[x]) {
You can't compute the deviation until you know the average of all the numbers, so you would need another loop to take care of that. Actually, if you do a little algebra on the deviation formula, you'll find that if you keep track of sum of x and the sum of x2, then you can compute the average and standard deviation directly from the sums.
Mmmh ok will re-work this and see what results i get. The test input file is hard coded so input values have already been inserted. will however try this out and see......Thanks guys