-
Standard Deviaiton issue
I have been working on this for a few days now and I still can't wrap my head around arrays and filling in arrays to compute the Standard Deviation of an input file.
This is what I have:
Code:
#include <fstream>#include <iostream>
#include <cmath>
using namespace std;
double get_standard_dev( double Num [], int x );
const int size= 100;
int main ()
{
int x, size;
double Num[x];
ifstream in_stream;
cout << "We are going to find the standard deviation for the file stddev.dat" << endl;
// Opens the input file.
in_stream.open ( "stddev.dat" );
// If the file fails to open it will close the program and output the statement.
if ( in_stream.fail( ) )
{
cout << "Please check if the file is saved properly. It could not open." << endl;
}
cout << get_standard_dev( Num, size) << endl;
return 0;
}
double get_standard_dev( double Num [], int x )
{
double average, temp, mean;
double sum = 0;
int i;
for( i = 0; i < x;i++ )
{
sum += Num[i];
}
average = sum / x;
for( i = 0; i < x;i++ )
{
temp = Num[i] - average;
sum += temp * temp;
}
mean = sum / x;
return sqrt(mean);
}
-
You are computing the population standard deviation. You probably want to compute the sample standard deviation. The calculations are similar, but give slightly different results (the difference in method being related to Bessel's correction being needed when computing the sample standard deviation).
If you don't understand what I'm saying, google is your friend.
-
I don't quite understand where I am messing up in this program. It is outputting 1 and I can't figure out why. Can anyone point me in the right direction?
Code:
- #include <fstream>
- #include <iostream>
- #include <cmath>
- using namespace std;
- double get_standard_dev( double Num [], int x );
- const int size= 100;
- int main ()
- {
- int next;
- int count = 0;
- double Num[size];
- for(int i =0; i < size; i++)
- {
- Num[i]=0;
- }
- ifstream in_stream;
- cout << "We are going to find the standard deviation for the file stddev.dat" << endl;
- // Opens the input file.
- in_stream.open ( "stddev.dat" );
- // If the file fails to open it will close the program and output the statement.
- if ( in_stream.fail( ) )
- {
- cout << "Please check if the file is saved properly. It could not open." << endl;
- return 0; // you want to end the program here. You can't calculate correctly if the file does not open
- }
- while(in_stream >> next)
- {
- Num[count]=next;
- count++;
- }
- get_standard_dev ( Num , count );
- // now read from in_stream into the Num[] array. Fill in x with the number of numbers in the file.
- // now close the file
- in_stream.close();
- return 0;
- }
- double get_standard_dev( double Num [], int x )
- {
- double average, s;
- double sum = 0;
- int i;
- for( i = 0; i < x;i++ )
- {
- sum = sum + Num[i];
- }
- average = sum / x;
- sum = 0;
- for( i = 0; i < x; i++ )
- {
- s =pow((Num[i]-average),2);
- //cout << s<<" ";
- sum = sum + s;
- }
- cout <<(sqrt (sum / x));
- return 0;
- }