class ComplexityAssert::SimpleLinearRegression

Performs basic linear regression on a set of points

Public Class Methods

new(xs, ys) click to toggle source
# File lib/complexity_assert/simple_linear_regression.rb, line 6
def initialize(xs, ys)
  @xs, @ys = xs, ys
  if @xs.length != @ys.length
    raise "Unbalanced data. xs need to be same length as ys"
  end
end

Public Instance Methods

mean(values) click to toggle source
# File lib/complexity_assert/simple_linear_regression.rb, line 34
def mean(values)
  total = values.reduce(0) { |sum, x| x + sum }
  Float(total) / Float(values.length)
end
slope() click to toggle source
# File lib/complexity_assert/simple_linear_regression.rb, line 19
def slope
  x_mean = mean(@xs)
  y_mean = mean(@ys)

  numerator = (0...@xs.length).reduce(0) do |sum, i|
    sum + ((@xs[i] - x_mean) * (@ys[i] - y_mean))
  end

  denominator = @xs.reduce(0) do |sum, x|
    sum + ((x - x_mean) ** 2)
  end

  (numerator / denominator)
end
y_intercept() click to toggle source

TODO cache all these instead of computing it every time

# File lib/complexity_assert/simple_linear_regression.rb, line 15
def y_intercept
  mean(@ys) - (slope * mean(@xs))
end