gpt4 book ai didi

objective-c - Objective-C : Calculate the standard deviation of an NSArray of NSNumber objects?

转载 作者:太空狗 更新时间:2023-10-30 03:22:34 26 4
gpt4 key购买 nike

如果我有 NSNumber 对象的 NSArray,我该如何计算数组中数字的标准偏差?

最佳答案

假设将所有 NSNumbers 处理为双倍长度 float 是安全的(所以如果你在范围的末端有一些 64 位整数,你会失去一些精度)并且我首先正确地记住了公式实现可以是:

- (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])];
}

关于objective-c - Objective-C : Calculate the standard deviation of an NSArray of NSNumber objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4889486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com