Module: Math

Defined in:
lib/least_squares.rb

Class Method Summary collapse

Class Method Details

.least_squares(xs, ys) ⇒ Proc

Takes two arrays of numbers and returns the Least Squares Regression Line as a Proc.

Examples:

xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ys = [9, 1, 0, 5, 4, 7, 7, 0, 9, 3]
ls = Math.least_squares(xs,ys)
(1..10).map{|i| ls.call(i)} #=> [4.2, 4.2667, 4.333, 4.4, 4.4667, 4.5333, 4.6, 4.667, 4.7333, 4.8]

Parameters:

  • xs (Array<Numeric>)

    Array of numbers

  • ys (Array<Numeric>)

    Array of numbers

Returns:

  • (Proc)

    Least Squares Regression Line



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.

Examples:

xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Math.mean(xs) #=> 5.5

Parameters:

  • xs (Array<Numeric>)

    Array of numbers

Returns:

  • (Float)

    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.

Examples:

xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ys = [9, 1, 0, 5, 4, 7, 7, 0, 9, 3]
Math.pearson(xs,ys) #=> 0.0581327470763432

Parameters:

  • xs (Array<Numeric>)

    Array of numbers

  • ys (Array<numeric>)

    Array of numbers

Returns:

  • (Float)

    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

.stdev(xs) ⇒ Float

Takes an array of numbers and returns the Standard Deviation.

Examples:

xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Math.stdev(xs) #=> 3.02765035409749

Parameters:

  • xs (Array<Numeric>)

    Array of numbers

Returns:

  • (Float)

    Standard Deviation



24
25
26
27
# File 'lib/least_squares.rb', line 24

def Math.stdev(xs)
  mean = Math.mean(xs)
  Math.sqrt((1/(xs.size.to_f - 1)) * xs.inject(0){|s,n| s + (n - mean)**2})
end