Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean and standard deviation from a vector of samples in C++ using Boost

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?

like image 758
user393144 Avatar asked Sep 30 '11 21:09

user393144


People also ask

How do you find the mean and standard deviation in C?

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);

How do you find the standard deviation of a vector?

S = std( A , w , vecdim ) computes the standard deviation over the dimensions specified in the vector vecdim when w is 0 or 1.

How do you find the mean in CPP?

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.

How do you find standard deviation and variance in C?

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.


1 Answers

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; }); 
like image 52
musiphil Avatar answered Sep 28 '22 15:09

musiphil