#include<iostream>
#include<cstdlib>
#include<cmath>
#include<sys/time.h>
int main(int argc, char** argv) {
using namespace std;
// read sample size from command line
if (argc < 2) {
cerr << "meanvariance: sample size needed on command line" << endl;
return 1;
}
int sampleSize = atoi(argv[1]);
if (sampleSize <= 0) {
cerr << "meanvariance: sample size must be strictly positive" << endl;
return 2;
}
// initialize randomizer
struct timeval theTV;
struct timezone theTZ;
gettimeofday(&theTV, &theTZ);
srandom(theTV.tv_usec);
// generate the sample (numbers between 0 and 1)
double* sample = new double[sampleSize];
for(int i = 0; i < sampleSize; i++) {
sample[i] = (double) random() / (double) RAND_MAX;
}
// compute the mean
double mean = 0;
for(int i = 0; i < sampleSize; i++) {
mean += sample[i];
}
mean /= (double) sampleSize;
// compute the variance
double variance = 0;
double dtmp = 0;
for(int i = 0; i < sampleSize; i++) {
dtmp = sample[i] - mean;
dtmp *= dtmp;
variance += dtmp;
}
variance /= (double) sampleSize;
// compute the standard deviation
double stddev = sqrt(variance);
// output
cout << "mean = " << mean << "; variance = " << variance
<< "; std deviation = " << stddev << endl;
delete [] sample;
return 0;
}
Let
a sample of size
of values of the random
variable
.
| Var |