Standard Deviation

Hello All, I have a question regarding SD. I am generating the numbers of 08 30 11 19 91 05 20 getting the a SD of 31.6812, how ever the correct SD SHOULD BE 29.7873

08 30 11 19 91 05 20

So far I am able to find mean, the median, but I have the wrong SD. Here is a part of the code which I'm having trouble on, on getting the SD.

double standardDeviation(int ar [], unsigned n)
for (int i = 0; i < n; i++)	
		sum = sum + ar[i];
	avg = sum / float(n);

	for (int i = 0; i <= n; i++)
		sum2 += pow(ar[i] - avg, 2);
	sD = sqrt(sum2 / (n - 1));
	return  static_cast<double>(sD);
Last edited on
Help Please
closed account (D80DSL3A)
You are exceeding array bounds on line 9. Should be < not <= , like you have on line 3. Hard to say what's wrong otherwise. There are 4 variables being used which aren't declared in the function: sum, sum2, avg and sD. I don't know their types (could affect accuracy and how operations are carried out) or the initial values of sum or sum2. Did you assign sum=0 and sum2=0 before calling the function?
Your standard deviation function is incomplete and contains error. It should not compile.

sum, avg, sum2 and sD are never declared and initialized.

Before the first for loop you need double sum = 0.0;

Line 7, put double before avg, double avg = sum / n; You do not need float in front of n. The compiler will automatically promote n to a double since sum is a double.

Before the second for loop you need double sum2 = 0.0;

Line 13, put double in front of sD, double sD = sqrt(sum2 / (n - 1));

You should get rid of the leading zeroes for 08 and 05 as the compiler will attempt to treat them as octal instead of decimal.

Line 14, since sD is a double you can eliminate the static_cast and just use return sD;

Using the supplied data I obtained a standard deviation of 29.7642

fun2code i had <= which instead should of been <. thank you for letting me cacth my error
Alrededor is also correct. If this is your function, then you have your internal variables declared globally.

This is very dangerous because if anyone attempts to use these labels, they will get unexpected results.

sum = 15;
sum += standardDeviation(myArray, size);

Here I would expect the sum to be 15 plus the standard deviation, but because it's a global label, it gets over-written by standardDeviation() without any clue why. In fact, even the standard deviation will be completely wrong because you don't set it to 0 in standardDeviation. The initial value for sum is 15, not 0 here so your calculation output will be completely wrong and it'll be a very tough thing to debug.
Originally When i had <= n on line 9 the sd was 32..... I didn't understand why until i had realize its was greater than or equal symbol i had inserted to which made a complete difference on the outcome.
Topic archived. No new replies allowed.