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

前端 未结 6 1823
心在旅途
心在旅途 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条回答
  •  猫巷女王i
    2020-12-28 21:29

    There is some good code on Rosetta Code for this. To go through your NSArray (instead of C array like they have in their example), just use this code along with their implementation of SDAccum:

    - (double)computeStandardDeviationWithArray:(NSArray *)numberArray
    {
        double sd;
        SDAccum *sdacc = [[SDAccum alloc] init];
    
        for(NSNumber *aNumber in numberArray)
        {
            sd = [sdacc value: [aNumber doubleValue]];
        }
    
        [sdacc release];
        return sd;
    }
    

提交回复
热议问题