Skip to content

Instantly share code, notes, and snippets.

@aceontech
Created December 17, 2014 10:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aceontech/abb1bf4345dccfb32f7d to your computer and use it in GitHub Desktop.
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.
//
// 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
//
// 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