### Calculate variance in C++?

I am using the valarray function to take the numbers in myarray, and subtract them from the mean to obtain the second array. Please see the attached image. It gives the results of the second array as Result 0, Result 1, etc.

The output will look like this:

The sum of the specified array is 3300
The maximum value of the specified array is 1000
The minimum value of the specified array is 20
The mean of the specified array is 330

Result 0: -310
Result 1: -290
Result 2: -270
Result 3: -250
Result 4: -230
Result 5: -210
Result 6: 70
Result 7: 270
Result 8: 470
Result 9: 670

My question is; how can I add up the values of the new numbers generated to then calculate variance as (sum of new array)/n-1? Any help appreciated. Please see the code below.

#include <iostream>
#include <cmath>
#include <valarray>

using namespace std;

int main()
{
int myarray[] = { 20, 40, 60, 80, 100, 200, 400, 600, 800, 1000 };

int mynumber;

int values;

std::cout << "Number of values in array: ";
std::cin >> values;

std::cout << "" << '\n';
std::valarray<int> myvalarray(myarray, values);

int mean;
mean = (myvalarray.sum()) / values;

std::cout << "The sum of the specified array is " << myvalarray.sum() << '\n';
std::cout << "The maximum value of the specified array is " << myvalarray.max() << '\n';
std::cout << "The minimum value of the specified array is " << myvalarray.min() << '\n';
std::cout << "The mean of the specified array is " << mean << '\n';

for (int i = 0; i < values; i++)
{
int myresult = myarray[i] - mean;
std::cout << "" << '\n';
std::cout << "Result " << i << ": ";
std::cout << myresult << "\n";

}

getchar();
getchar();
return 0;
}
Why can't you just `myarray -= mean;`?
Then print it, and then use it to calculate the variance.
Hope this helps.
Topic archived. No new replies allowed.