Thursday, February 3, 2011

Standard deviation

Consider a population consisting of the following eight values:

    2,\  4,\  4,\  4,\  5,\  5,\  7,\  9
These eight data points have the mean (average) of 5:

    \frac{2 + 4 + 4 + 4 + 5 + 5 + 7 + 9}{8} = 5
To calculate the population standard deviation, first compute the difference of each data point from the mean, and square the result of each:

    \begin{array}{lll}
    (2-5)^2 = (-3)^2 = 9   &&  (5-5)^2 = 0^2 = 0 \\
    (4-5)^2 = (-1)^2 = 1  &&  (5-5)^2 = 0^2 = 0 \\
    (4-5)^2 = (-1)^2 = 1  &&  (7-5)^2 = 2^2 = 4 \\
    (4-5)^2 = (-1)^2 = 1  &&  (9-5)^2 = 4^2 = 16
    \end{array}
Next compute the average of these values, and take the square root:

    \sqrt{ \frac{9 + 1 + 1 + 1 + 0 + 0 + 4 + 16}{8} } = 2
This quantity is the population standard deviation; it is equal to the square root of the variance. The formula is valid only if the eight values we began with form the complete population. If they instead were a random sample, drawn from some larger,  parent” population, then we should have used 7 (n − 1) instead of 8 (n) in the denominator of the last formula, and then the quantity thus obtained would have been called the sample standard deviation. See the section Estimation below for more details

------------------------------------------------------------------------
#include <math.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
 int xn=0, N = 30;
 double x[N],m=0,s=0;
 string filename,outfilename;
   ifstream instream;
  
   cout<<"file"<<endl;
 cin>>filename;                        
 instream.open(filename.c_str());
 cout <<"successful"<<endl;

while(xn != N)
{
 instream >> x[xn];
// cout << "x"<<xn << " = " << x[xn] << endl;
 xn++;
 }

 for(xn=0;xn!=N;xn++)
 {
  m=m+x[xn];
  }
 
 m=m/N;
 cout<<"median = "<<m<<endl;

 for(xn=0;xn!=N;xn++)
 {
  s=s+(x[xn]-m)*(x[xn]-m);
  }

 s=sqrt(s/N);
 cout<<"standard deviation = "<<s<<endl;

/*cout<<"outfile"<<endl;
cin>>outfilename;
ofstream outfile(outfilename.c_str());
for(xn=0;xn!=N;xn++)
{
 outfile<<xn<<" "<<x[xn];
 if(xn%2 != 0){outfile<<endl;}
 else{outfile<<" ";}
 }*/
cout<<"done"<<endl;
return 0;
 }

 
-------------------------------------------

No comments:

Post a Comment