I have already spent about an hour on this piece of code. There must be some sneaky bugs lurking somewhere. I implore you, o Wise One, please enlighten this ignorant newbie...
A bunch of integers are given as a vector, and their mean is known. I want to calculate their standard deviation.
double sd(const std::vector<int> &results, double mean)
{
int n = results.size(); // getting the sample size
// summing over (deviation)^2
double temp = 0;
for(int i = 0; i < n; i++)
{
temp += ((double) results[i] - mean)*( (double)results[i] - mean);
};
// this is the variance
double temp2 = temp / (double)(n-1);
// take sqrt for standard deviation
return std::sqrt(temp2);
};
This code gave rubbish when I plugged it into my main program. I then tested it using random integers between [0, 10], and it always returns 1 no matter what...
(The mean has been fluctuating around 5, so I know the random number is working.)
The renaming of variables was to clean up some less-than-decent language included in the code out of my frustration. And well that inevitably introduced typos...
Did you read what I wrote?! So, please, do not bother any more the forum until you did not check values of the vector and the return value in your function.
I can suspect that values of the vector are not the same as you are assuming. Maybe you should substitute std::vector<int> for std::vector<double>