我写了一个简单的类叫做MovingAverage来处理这个问题。你可以使用init方法初始化该方法,并保持其余部分的样本计数的模来知道要将其放入哪一个静态插槽中。
使用以下内容进行初始化:
MovingAverage *avg5periods = [[MovingAverage alloc] initWithSize:5]
添加项目:
[avg5periods addSample:1.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
[avg5periods addSample:2.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
[avg5periods addSample:3.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
[avg5periods addSample:4.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
[avg5periods addSample:5.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
[avg5periods addSample:6.0];
NSLog(@"1.2f",[avg5periods movingAverage]);
头文件:
#import <Foundation/Foundation.h>
@interface MovingAverage : NSObject {
NSMutableArray *samples;
int sampleCount;
int averageSize;
}
-(id)initWithSize:(int)size;
-(void)addSample:(double)sample;
-(double)movingAverage;
@end
实现文件:
#import "MovingAverage.h"
@implementation MovingAverage
-(id)initWithSize:(int)size {
if (self = [super init]) {
samples = [[NSMutableArray alloc] initWithCapacity:size];
sampleCount = 0;
averageSize = size;
}
return self;
}
-(void)addSample:(double)sample {
int pos = fmodf(sampleCount++, (float)averageSize);
[samples setObject:[NSNumber numberWithDouble:sample] atIndexedSubscript:pos];
}
-(double)movingAverage {
return [[samples valueForKeyPath:@"@sum.doubleValue"] doubleValue]/(sampleCount > averageSize-1?averageSize:sampleCount);
}
@end