class MovingAverage

A class to efficiently perform Moving Average calculations. Calculating moving averages of length m on a set of data of length n requires Θ(m) storage and Θ(n) work.

Author

Paul J Sanchez (pjs at alum.mit.edu)

Copyright

Copyright © 2018 Paul J Sanchez

License

MIT

Attributes

m[R]

Number of elements in the moving average

Public Class Methods

new(m) click to toggle source

Initialize the MovingAverage object.

Arguments
  • m -> the number of elements to be averaged

Raises
  • RuntimeError if m < 1

# File lib/datafarming/moving_average.rb, line 23
def initialize(m)
  fail 'Number of terms to avg (m) must be strictly positive' if m < 1
  @m = m
  @current_set = Array.new(@m)
  @current_avg = 0.0
  @current_count = 0
end

Public Instance Methods

new_obs(x) click to toggle source

Add a new observation, get the resulting moving average.

Arguments
  • x -> the number of elements to be averaged

Raises
  • RuntimeError if x is non-numeric

Returns
  • Average of the last m observations, or nil if fewer than m values have been processed.

# File lib/datafarming/moving_average.rb, line 42
def new_obs(x)
  x = x.to_f
  if @current_count < @m
    @current_set[@current_count] = x
    @current_count += 1
    @current_avg += (x - @current_avg) / @current_count
    @current_count == @m ? @current_avg : nil
  else
    @current_set << x
    @current_avg += (x - @current_set.shift) / @m
  end
end