Module: Philiprehberger::MathKit::MovingAverage
- Defined in:
- lib/philiprehberger/math_kit/moving_average.rb
Class Method Summary collapse
-
.exponential(values, alpha:) ⇒ Array<Float>
Exponential moving average.
-
.simple(values, window:) ⇒ Array<Float>
Simple moving average.
Class Method Details
.exponential(values, alpha:) ⇒ Array<Float>
Exponential moving average
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/philiprehberger/math_kit/moving_average.rb', line 28 def exponential(values, alpha:) raise ArgumentError, 'values must not be empty' if values.empty? raise ArgumentError, 'alpha must be between 0 (exclusive) and 1 (inclusive)' if alpha <= 0 || alpha > 1 result = [values.first.to_f] values[1..].each do |v| result << ((alpha * v) + ((1 - alpha) * result.last)) end result end |
.simple(values, window:) ⇒ Array<Float>
Simple moving average
13 14 15 16 17 18 19 20 |
# File 'lib/philiprehberger/math_kit/moving_average.rb', line 13 def simple(values, window:) raise ArgumentError, 'window must be at least 1' if window < 1 raise ArgumentError, 'window must not exceed values size' if window > values.size (0..(values.size - window)).map do |i| values[i, window].sum.to_f / window end end |