Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C: Calculate the standard deviation of an NSArray of NSNumber objects?

If I have an NSArray of NSNumber objects, how do I calculate the standard deviation of the numbers in the array?

like image 390
Clay Avatar asked Feb 03 '11 17:02

Clay


2 Answers

Assuming it's safe to process all NSNumbers as double length floats (so you'll lose some precision if you've got some 64 bit integers at extreme ends of the range in there) and I've remembered the formula correctly a first implementation could be:

- (NSNumber *)meanOf:(NSArray *)array
{
    double runningTotal = 0.0;

    for(NSNumber *number in array)
    {
        runningTotal += [number doubleValue];
    }

    return [NSNumber numberWithDouble:(runningTotal / [array count])];
}

- (NSNumber *)standardDeviationOf:(NSArray *)array
{
    if(![array count]) return nil;

    double mean = [[self meanOf:array] doubleValue];
    double sumOfSquaredDifferences = 0.0;

    for(NSNumber *number in array)
    {
         double valueOfNumber = [number doubleValue];
         double difference = valueOfNumber - mean;
         sumOfSquaredDifferences += difference * difference;
    }

    return [NSNumber numberWithDouble:sqrt(sumOfSquaredDifferences / [array count])];
}
like image 143
Tommy Avatar answered Nov 12 '22 07:11

Tommy


You can use NSExpression built-in functions.

NSArray *numbers = @[@1, @2, @3, @4, @5, @6, @7, @8];
NSExpression *expression = [NSExpression expressionForFunction:@"stddev:" arguments:@[[NSExpression expressionForConstantValue:numbers]]];
NSNumber *value = [expression expressionValueWithObject:nil context:nil];
NSLog(@"%@,", value); // => 2.29128...

For more information check the official documentation and this NSHipster article.

like image 26
Tiago Avatar answered Nov 12 '22 07:11

Tiago