S
silverburgh.meryl
I have a function which calculate standard deviation. I am trying to
re-write it using STL algorithm.
I am thinking of using for_each() algorithm, but that will require my
function passing in to have state (e.g. the value of standard deviation
sum). I read some online article that having state is not a good
idea. So is there a better solution?
Thank you.
/**
Calculate the standard deviation, given the mean of the numbers
*/
double sd( const vector<int>& v,
const double mean )
{
double stdDev = 0.0;
int N = v.size();
const double mean_ = mean;
// calculate the standard deviation sum
double stdDevSum = 0;
double x;
for (int i = 0; i < N; i++) {
x = v - mean_;
stdDevSum = stdDevSum + (x * x);
}
double variance = stdDevSum / static_cast<double>(N-1);
stdDev = sqrt( variance );
return stdDev;
} // sd
re-write it using STL algorithm.
I am thinking of using for_each() algorithm, but that will require my
function passing in to have state (e.g. the value of standard deviation
sum). I read some online article that having state is not a good
idea. So is there a better solution?
Thank you.
/**
Calculate the standard deviation, given the mean of the numbers
*/
double sd( const vector<int>& v,
const double mean )
{
double stdDev = 0.0;
int N = v.size();
const double mean_ = mean;
// calculate the standard deviation sum
double stdDevSum = 0;
double x;
for (int i = 0; i < N; i++) {
x = v - mean_;
stdDevSum = stdDevSum + (x * x);
}
double variance = stdDevSum / static_cast<double>(N-1);
stdDev = sqrt( variance );
return stdDev;
} // sd