Class: MovingAverage

Inherits:
Object
  • Object
show all
Defined in:
lib/datafarming/moving_average.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(m) ⇒ MovingAverage

Initialize the MovingAverage object.

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

Raises
  • RuntimeError if m < 1



23
24
25
26
27
28
29
# 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

Instance Attribute Details

#mObject (readonly)

Number of elements in the moving average



13
14
15
# File 'lib/datafarming/moving_average.rb', line 13

def m
  @m
end

Instance Method Details

#new_obs(x) ⇒ Object

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.



42
43
44
45
46
47
48
49
50
51
52
53
# 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