public
Description: agile project management
Homepage: http://mutuallyhuman.com
Clone URL: git://github.com/mvanholstyn/strac.git
strac / lib / linear_regression.rb
100644 42 lines (33 sloc) 0.723 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class LinearRegression
 
  def initialize xs, ys
    @slope = calculate_slope xs, ys
    @intercept = calculate_intercept @slope, xs, ys
  end
  
  attr_reader :slope, :intercept
  
  def [](x)
    @intercept + @slope*x
  end
  
  private
  
  def sum(arr)
    arr.inject(0.0){ |sum, x|
      sum + x
    }
  end
  
  def sum_products(xs, ys)
    xs.zip(ys).inject(0.0){|result, (x,y)|
      result + x*y
    }
  end
  
  def sum_squares(xs)
    xs.inject(0.0) {|result, x|
      result + x*x
    }
  end
  
  def calculate_slope(xs, ys)
    n = xs.size
    (n*sum_products(xs, ys) - sum(xs)*sum(ys)) / (n*sum_squares(xs) - sum(xs)**2)
  end
  
  def calculate_intercept(m, xs,ys)
    (sum(ys) - m*sum(xs))/xs.size
  end
end