Standard deviation problem

Hey. I'm trying to write a program that calculates the standard deviation. Visual basic doesn't give me any errors, but I think that the result is wrong.
Can anyone see whats wrong?
My code:(not all of the code, but the problem should lie here)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
else
	{
		for(n=0; n<choosenNum; n++)
		{
			cout<< "Enter Number: ";
			cin>>arrayNum[n];
		}
	}
	int sum = 0;
	
	for (int j = 0; j < choosenNum; j++) //Sum of values
	{
		sum += arrayNum[j];
	}
	cout <<"Sum of the numbers: " <<sum << endl << endl; 

	double meanValue = CalcMeanValue(choosenNum, sum); // Method call for CalcMeanValue

	cout << "Mean value: " << meanValue << endl;
	
	double deviation;
	
	
	double stanDev = CalcStanDev(deviation, meanValue, arrayNum[n], choosenNum); //Method call for CalcStanDev

	cout << "Standard Deviation: " << stanDev;
	
	
	Console::ReadKey();
}
double CalcMeanValue(double choosenNum, double sum) // Method for calculating the mean value
{

return sum / choosenNum;

}
double CalcStanDev(double deviation, double meanValue, double diffValues, int nValues)
{
	return deviation = sqrt((pow((diffValues - meanValue),2))/(nValues-1)); //Calculation of the deviation

	
}
The CalcStanDev is wrong.

You call it like this:
CalcStanDev(deviation, meanValue, arrayNum[n], choosenNum);

The first problem is that arrayNum[n] is out of bounds because n currently represents the number of elements in the array.

The second problem is that even if n wasn't out of bounds, you're just passing a data member into CalcStanDev. This isn't the equation.

You want something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double Avg(double Values[], int nValues)
{
    double sum = 0;
    for (int i = 0; i < nValues; ++i)
        sum += Values[i];
    return sum / (double(nValues));
}

double StDev(double Values[], int nValues)
{
    double mean = Avg(Values, nValues);

    double sumSquared = 0;
    for (int i = 0; i < nValues; ++i)
        sumSquared += (Values[i] - mean) * (Values[i] - mean);
        
    return sqrt(sumSquared) / (double(nValues) - 1.);
}


In general, you want to do everything you can inside of a function. The main() should only be used for higher level operations. So when we compute an average, we want to do the summing inside of the function, not outside. We also want to make the interface (parameter list) as simple as possible. In both cases of calculating the Average and StDev, all we need is the list of numbers and the number of values.
Last edited on
I don't believe this works. You need to return the sqrt of the variance, you are returning the sqrt of the numerator.

return sqrt(sumSquared/(double(nValues)-1));
Topic archived. No new replies allowed.