As defined: Average refers to the sum of numbers divided by n. That is, when dealing with an average, you usually have at least 2 or more observations from which you wish to calculate an average. The average of your current speed is just, well, your current speed divided by one. I'm sure that's not what you are looking for.
You will need to ask yourself for how long time you wish to average. Five seconds? 10 seconds? The shorter the interval (fewer observations), the more sensitive to significant changes your average will be.
Basically what you would do is to store your observations in a mutable collection, eg NSMutableArray
, and then just sum them up and divide the sum by the array's count
property, corresponding to the number of observations. Or, as NSHipster has a great article on, you could take advantage of valueForKeyPath
:
NSMutableArray *speedObservations = [[NSMutableArray alloc] initWithCapacity:n];
...
CGFloat average = [speedObservations valueForKeyPath:@"@avg.floatValue"];