Is there a way to calculate mean and standard deviation for a vector containing samples using Boost?
Or do I have to create an accumulator and feed the vector into it?
sum += (num[i] - mean) * (num[i] - mean); SD = sqrt(sum / n); // Calculating Standard Deviation sum = 0.0; for (i = 0; i < n; i++) sum += (num[i] - mean) * (num[i] - mean); SD = sqrt(sum / n);
S = std( A , w , vecdim ) computes the standard deviation over the dimensions specified in the vector vecdim when w is 0 or 1.
Then the mean is found by dividing the sum by the number of elements. This is given in the following code snippet. for(i = 0; i < 5; ++i) sum += val[i]; mean = sum/5; The variance of the data is found by squaring the differences from the mean, adding them and then finding their average.
The formula which is used in this program is mean = average of the numbers. variance = (summation( ( Xi – average of numbers) * ( Xi – average of numbers)) ) / Total no of elements. where i = 1 to N here N is the total no of elements. Standard deviation = Squareroot of the variance.
I don't know if Boost has more specific functions, but you can do it with the standard library.
Given std::vector<double> v
, this is the naive way:
#include <numeric> double sum = std::accumulate(v.begin(), v.end(), 0.0); double mean = sum / v.size(); double sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), 0.0); double stdev = std::sqrt(sq_sum / v.size() - mean * mean);
This is susceptible to overflow or underflow for huge or tiny values. A slightly better way to calculate the standard deviation is:
double sum = std::accumulate(v.begin(), v.end(), 0.0); double mean = sum / v.size(); std::vector<double> diff(v.size()); std::transform(v.begin(), v.end(), diff.begin(), std::bind2nd(std::minus<double>(), mean)); double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); double stdev = std::sqrt(sq_sum / v.size());
UPDATE for C++11:
The call to std::transform
can be written using a lambda function instead of std::minus
and std::bind2nd
(now deprecated):
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With