If I have an NSArray
of NSNumber
objects, how do I calculate the standard deviation of the numbers in the array?
Here is another version I've used some time ago.
NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:...],
[NSNumber numberWithInt:...],
[NSNumber numberWithInt:...], nil];
// Compute array average
int total = 0;
int count = [numbers count];
for (NSNumber *item in numbers) {
total += [item intValue];
}
double average = 1.0 * total / count;
// Sum difference squares
double diff, diffTotal = 0;
for (NSNumber *item in numbers) {
diff = [item doubleValue] - average;
diffTotal += diff * diff;
}
// Set variance (average from total differences)
double variance = diffTotal / count; // -1 if sample std deviation
// Standard Deviation, the square root of variance
double stdDeviation = sqrt(variance);