Class: AdvancedMath::SimpleMovingAverage
- Inherits:
-
Object
- Object
- AdvancedMath::SimpleMovingAverage
- Defined in:
- lib/advanced_math.rb
Overview
Simple Moving Average (SMA) calculator Created: 2011-06-24 Author: G Nagel Company: Mercury Wireless Software LLC
Direct Known Subclasses
Instance Method Summary collapse
-
#add(value) ⇒ Object
Add a value to the list.
-
#initialize(range) ⇒ SimpleMovingAverage
constructor
Initialize the members: range: number of values to average sum: current sum of all values in the array values: array of values used as temporary storage.
Constructor Details
#initialize(range) ⇒ SimpleMovingAverage
Initialize the members: range:
number of values to average
sum:
current sum of all values in the array
values:
array of values used as temporary storage
20 21 22 23 24 25 26 |
# File 'lib/advanced_math.rb', line 20 def initialize(range) raise ArgumentError, "Range is nil" unless (range); raise ArgumentError, "Range must be >= 1" unless range.to_i >= 1; @range = range.to_i; @sum = 0; @values = Array.new(); end |
Instance Method Details
#add(value) ⇒ Object
Add a value to the list. If the list is < @range, then return nil. Otherwise compute the SMA and return the value.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/advanced_math.rb', line 33 def add(value) raise ArgumentError, "Value is nil" unless (value); # add the value to the end of the array. @values.push(value); # Calculate the sum of the array @sum += value.to_f; # Is the array less than the range? return nil if (@values.length() < @range) # Is the array larger than the range? @sum -= @values.shift.to_f() if (@values.length() > @range) # Compute the average return @sum.to_f / @range.to_f; end |