Linear regression in Ruby

Let’s say you have the following 5 numbers:

values = [100, 200, 300, 400, 500]

To predict the next 3 in this series you need linear regression:

def linear_regression(pairs)
  n = pairs.size

  sum_x = pairs.map { |x, _| x }.sum.to_f
  sum_y = pairs.map { |_, y| y }.sum.to_f

  sum_xx = pairs.map { |x, _| x * x }.sum.to_f
  sum_xy = pairs.map { |x, y| x * y }.sum.to_f

  a = (    n * sum_xy - sum_x * sum_y ) / (n * sum_xx - sum_x**2)
  b = (sum_y * sum_xx - sum_x * sum_xy) / (n * sum_xx - sum_x**2)

  [a, b]
end

Call the function above with pairs of [index, value]:

def predict_next(count, values)
  pairs = []
  values.each_with_index { |e, i| pairs << [i, e] }

  a, b = linear_regression(pairs)
  n    = values.size

  result = []
  count.times { |i| result << a * (i + n) + b }
  result
end

Now you can call the #predict_next/2 function:

values = [100, 200, 300, 400, 500]
pp predict_next(3, values)

It will display your result:

[600.0, 700.0, 800.0]