Created
December 17, 2014 10:47
-
-
Save aceontech/abb1bf4345dccfb32f7d to your computer and use it in GitHub Desktop.
Objective-C utility class for maintaining a moving average over a given time period.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Alex Manarpies on 12/17/14. | |
// | |
#import <Foundation/Foundation.h> | |
/** | |
* Utility class for maintaining a moving average over a given time period. | |
* Credits: http://stackoverflow.com/a/14740836/331283 | |
*/ | |
@interface MovingAverage : NSObject | |
@property(nonatomic, readonly) double movingAverage; | |
@property(nonatomic, readonly) double cumulativeAverage; | |
- (instancetype)initWithPeriod:(NSUInteger)period; | |
- (void)addDatum:(NSNumber *)datum; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Alex Manarpies on 12/17/14. | |
// | |
#import "MovingAverage.h" | |
@interface MovingAverage () | |
@property(nonatomic, strong) NSMutableArray *queue; | |
@property(nonatomic) NSUInteger period; | |
@property(nonatomic) NSUInteger count; | |
@property(nonatomic, readwrite) double movingAverage; | |
@property(nonatomic, readwrite) double cumulativeAverage; | |
@end | |
@implementation MovingAverage | |
- (instancetype)initWithPeriod:(NSUInteger)period { | |
self = [self init]; | |
if (self) { | |
_period = period; | |
_queue = [[NSMutableArray alloc] initWithCapacity:period]; | |
} | |
return self; | |
} | |
- (void)addDatum:(NSNumber *)datum { | |
[self.queue insertObject:datum atIndex:0]; | |
double removed = 0; | |
double datumd = [datum doubleValue]; | |
if (self.queue.count > self.period) { | |
removed = [[self.queue lastObject] doubleValue]; | |
[self.queue removeLastObject]; | |
} | |
self.movingAverage = self.movingAverage - (removed / self.period) + (datumd / self.period); | |
self.cumulativeAverage = self.cumulativeAverage + (datumd - self.cumulativeAverage) / ++self.count; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment