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

前端 未结 6 1707
心在旅途
心在旅途 2020-12-28 21:04

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

6条回答
  •  隐瞒了意图╮
    2020-12-28 21:38

    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);
    

提交回复
热议问题