Calculating Standard Deviation

I'm having a problem calculating the standard deviation of an array.

I'm using numbers 1,2,3,4,5 to check the code and the standard deviation should be 1.58, but the program is saying it is 1. Does anybody know what is wrong with the code? I was going back and forth on storing the individual deviations in a n array.

Here is my code so far.

1
2
3
4
5
6
7
8
9
10
11
12
double stdDev(double s[], int size)
{
	double arrayDev[100], arrayDev_sum(0), stand_dev;

	for (int i=0; i < size; i++)
	{
		arrayDev[i] = pow((s[i] - average(s, size)),2);
		arrayDev_sum = arrayDev_sum + arrayDev[i]; 
	}
	stand_dev = sqrt((arrayDev_sum / size-1));
	return (stand_dev);
}



Last edited on
I just thought about precedence of the operators and I put parenthesis around size-1 on line 10 and the standard deviation value is correct now.

This was some other code I wrote to try to calculate the standard deviation. I'm not sure if this could have been done without using an array like I tried to do with the code below. I'm guessing it could, but it's just trickier.

1
2
3
4
5
6
7
8
9
10
11
12
13
double stdDev(double s[], int size)
{
	double indivDev, indivDev_squared, indivDev_squared_sum(0), stand_dev;

	for (int i=0; i < size; i++)
	{
		indivDev = s[i] - average(s, size);
		indivDev_squared = pow(indivDev,2);
		indivDev_squared_sum = indivDev_squared_sum + indivDev; 
	}
	stand_dev = sqrt((indivDev_squared_sum / (size-1)));
	return (stand_dev);
}
How does it work if you split line 10 into 2 lines? Something like:

1
2
 tempvar = arrayDev_sum /  (size-1);
stand_dev = sqrt (tempvar);


actually, now that I think about it, should line 10 be like:

stand_dev = sqrt((arrayDev_sum / (size-1)));

This way you can be certain the size-1 is occurring before the division.

Edit: Oops, now I see you caught that already. :)
Last edited on
What is the point of arrayDev being an array? It seems like you could just make it a double, remove its indexing in the loop, and the function would work exactly the same.

Also, it would be better to calculate the average once before the loop and use that value, rather than calculating the same average each time the loop iterates.

Edit: here's what it would look like with my changes:
1
2
3
4
5
6
7
8
9
10
11
12
13
double stdDev(double s[], int size)
{
	double arrayDev_sum(0), arrayAve, stand_dev;

                arrayAve = average(s, size);

	for (int i=0; i < size; i++)
	{
		arrayDev_sum += pow((s[i] - arrayAve),2);
	}
	stand_dev = sqrt(arrayDev_sum / (size-1));
	return stand_dev;
}


Looks like you don't need arrayDev at all. I didn't test my code at all though.
Last edited on
Topic archived. No new replies allowed.