# Mean, Variance, Squaring

• 09-06-2010
Kat007
Mean, Variance, Squaring
Hello,

Does C++ have built in function for finding mean and variance of a sequence of numbers?

Also if I have an expression

(a - b) and I would like it squared, is there an equivalent to Matlab's
(a - b)^2?

The reason I ask that is that if I have to write out variance calculation mannually, I'd have to say:
Code:

```sqrt( (a-mean)^2 + (b-mean)^2 + ... + (n-mean)^2)/n) // My inputs have quite long names and it would look clumbersome to say sqrt( (a-mean)*(a-mean) + (b-mean)* (b-mean) + ... + (n-mean)*(n-mean))/n)```
• 09-06-2010
bernt
Quote:

(a - b) and I would like it squared, is there an equivalent to Matlab's
(a - b)^2?
The C math library (link) has some stuff like that. Nothing terribly special though - just all the basic functions (e^x, log, pow, trig, etc). So to answer your question:
Code:

```#include <math.h> //#include <cmath> instead for C++ environments ... double ans = pow(a, b); //double = a^b```
but IMO it's just easier to write out the multiplication for squares.

Quote:

sqrt( (a-mean)*(a-mean) + (b-mean)* (b-mean) + ... + (n-mean)*(n-mean))/n)
You could instead add the numbers in a loop. So instead of using variables a-n, you have an array of numbers.
Code:

```double numbers[n]; //fill array with values here: numbers[0]=3, numbers[1] =6, etc. double sum=0; int i; for (i=0; i<n; i++) {     sum+=(numbers[i]-mean)*(numbers[i]-mean); } double answer = sqrt(sum / n);```
• 09-07-2010
Kat007
Thank you very much, yes I've used the last idea you suggested. It is looking much neater that way. ;)
• 09-07-2010
hk_mp5kpdw
If/when you get more familiar with the STL, you can look at the numeric header which has some neat items in it. The inner_product function in particular looks like it can be used to compute variance in a somewhat compact form:
Code:

```#include <iostream> #include <numeric> #include <functional> #include <cmath> struct deviation_func {     double mean;     deviation_func(double _mean) : mean(_mean) {}     double operator()(double lhs,double rhs)     {         return (lhs-mean) * (rhs-mean);     } }; int main() {     double arr[] = {2,4,4,4,5,5,7,9};     const int num_vals = sizeof(arr)/sizeof(arr[0]);     double mean = std::accumulate(arr,arr+num_vals,0.0)/num_vals;     deviation_func foo(mean);     double variance = std::inner_product(arr,arr+num_vals,arr,0.0,std::plus<double>(),foo)/num_vals;     double standard_dev = std::sqrt(variance);     std::cout << "Arithmetic mean is    : " << mean << std::endl;     std::cout << "Population variance is: " << variance << std::endl;     std::cout << "Standard deviation is : " << standard_dev << std::endl;     return 0; }```
Whether it actually makes things more complicated looking or not is a matter of individual opinion. A simple loop might be best in many cases for clarity. Output of above program is below: