Module: Math
- Defined in:
- lib/least_squares.rb
Class Method Summary collapse
-
.least_squares(xs, ys) ⇒ Proc
Takes two arrays of numbers and returns the Least Squares Regression Line as a Proc.
-
.mean(xs) ⇒ Float
Takes an array of numbers and returns the Mean.
-
.pearson(xs, ys) ⇒ Float
Takes two arrays of numbers and returns the Pearson’s Correlation Coefficient.
-
.stdev(xs) ⇒ Float
Takes an array of numbers and returns the Standard Deviation.
Class Method Details
.least_squares(xs, ys) ⇒ Proc
Takes two arrays of numbers and returns the Least Squares Regression Line as a Proc.
62 63 64 65 66 |
# File 'lib/least_squares.rb', line 62 def Math.least_squares(xs, ys) b = Math.pearson(xs,ys) * (Math.stdev(ys) / Math.stdev(xs)) a = Math.mean(ys) - (b * Math.mean(xs)) lambda{|x| a + (b * x)} end |
.mean(xs) ⇒ Float
Takes an array of numbers and returns the Mean.
11 12 13 |
# File 'lib/least_squares.rb', line 11 def Math.mean(xs) xs.inject{|s,n| s+n} / xs.size.to_f end |
.pearson(xs, ys) ⇒ Float
Takes two arrays of numbers and returns the Pearson’s Correlation Coefficient.
41 42 43 44 45 46 47 |
# File 'lib/least_squares.rb', line 41 def Math.pearson(xs, ys) xs_mean = Math.mean(xs) ys_mean = Math.mean(ys) numerator = xs.zip(ys).inject(0){|s,n| s + ((n[0] - xs_mean) * (n[1] - ys_mean))} denominator = Math.sqrt(xs.inject(0){|s,x| s + (x - xs_mean) ** 2}) * Math.sqrt(ys.inject(0){|s,y| s + (y - ys_mean) ** 2}) numerator / denominator end |