Module: MoreMath::Sequence::MovingAverage
- Included in:
- MoreMath::Sequence
- Defined in:
- lib/more_math/sequence/moving_average.rb
Overview
Module containing moving average calculation methods
Provides simple moving average functionality for sequence analysis and time series data.
Instance Method Summary collapse
-
#simple_moving_average(n) ⇒ Array<Float>
(also: #moving_average)
Calculates a simple moving average for the sequence.
Instance Method Details
#simple_moving_average(n) ⇒ Array<Float> Also known as: moving_average
Note:
The result array will contain (elements.size - n + 1) elements
Note:
Each moving average is calculated as the arithmetic mean of n consecutive elements
Calculates a simple moving average for the sequence
A simple moving average is calculated by taking the arithmetic mean of a specified number of consecutive elements in the sequence.
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/more_math/sequence/moving_average.rb', line 29 def simple_moving_average(n) n < 1 and raise ArgumentError, 'n < 1, has to be >= 1' n <= @elements.size or raise ArgumentError, 'n > #elements, has to be <= #elements' avg = [] 0.upto(@elements.size - n) do |i| sum = 0.0 i.upto(i + n - 1) do |j| sum += @elements[j].to_f end avg << sum / n end avg end |