template<typename _It>
double SampleStandardDeviation(_It it1, _It it2)
{
return SampleStandardDeviationInternal(
it1,
it2,
_It::iterator_category()
);
}
template<typename _It>
double SampleStandardDeviationInternal(
_It it1,
_It it2,
std::input_iterator_tag
)
{
// Calculate the length of the sequence and the sum of
// the values.
//
int nNumPoints = 0;
double dblSum = 0.0;
double dblSsq = 0.0;
while( it1 != it2 )
{
dblSum += *it1;
dblSsq += *it1 * *it1;
++nNumPoints;
++it1;
}
// Return the sample standard deviation.
double n = static_cast<double>(nNumPoints);
return nNumPoints <= 1 ? 0.0 : (dblSsq - dblSum * dblSum / n) /
(n - 1.0) ;
}
template<typename _It>
double SampleStandardDeviationInternal(
_It it1,
_It it2,
std::random_access_iterator_tag
)
{
// Calculate the length of the sequence and the sum of
// the values.
//
double dblNumPoints = static_cast<double>(it2 - it1);
double dblSum = 0.0;
double dblSsq = 0.0;
while( it1 != it2 )
{
dblSum += *it1;
dblSsq += *it1 * *it1;
++it1;
}
// Return the sample standard deviation.
return dblNumPoints <= 1 ? 0.0 :
(dblSsq - dblSum * dblSum / dblNumPoints) / (dblNumPoints - 1.0) ;
}
End of Listing