Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Examples
- # [1,1,2,1,1,2,2].moving_average(2) => [1, 1, 1, 2]
- class Array
- # Calculates the moving average
- # given a Integer as a increment period
- def moving_average(increment = 1)
- return self.average if increment == 1
- a = self.dup
- result = []
- while(!a.empty?)
- data = a.slice!(0,increment)
- result << data.average
- end
- result
- end
- # Calculates the average
- def average
- (self.sum/self.size)
- end
- end
Add Comment
Please, Sign In to add comment