I’m working on a project that does some graphing, I and needed to do a linear best fit. A quick google search didn’t find the ruby code snippet I was looking for, so I converted one from PHP. ( Original nasty looking quasi-OO PHP source ) Sorry, no unit tests :)


class LinearRegression
  attr_accessor :slope, :offset

  def initialize dx, dy=nil
    @size = dx.size
    dy,dx = dx,axis() unless dy  # make 2D if given 1D
    raise "arguments not same length!" unless @size == dy.size
    sxx = sxy = sx = sy = 0
    dx.zip(dy).each do |x,y|
      sxy += x*y
      sxx += x*x
      sx  += x
      sy  += y
    end
    @slope = ( @size * sxy - sx*sy ) / ( @size * sxx - sx * sx )
    @offset = (sy - @slope*sx) / @size
  end

  def fit
    return axis.map{|data| predict(data) }
  end

  def predict( x )
    y = @slope * x + @offset
  end

  def axis
    (0...@size).to_a
  end
end

UPDATE: a few people have asked for usage instructions…

For a basic graph, just pass an array to the constructor.


lr = LinearRegression.new( [ 5,1,3,7,10,3,5 ] )
fitted_array = lr.fit
puts "The slope is #{lr.slope}" 

The second argument to the constructor (y-axis) is implied as [0,1,2,3,4,5,6,7] (starting with zero, incrementing by 1) You can pass it a different array for this second argument if you need to.

actionmailer ActionView ActiveRecord activesupport agile ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby console controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factories factories-and-workers factory pattern filemerge find and replace finder fink fixtures fun functional testing gem git google maps haml helper helpers imagemagick Intertrust irb javascript jquery jrails logo macro math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism project management prototype.js rails rails gotcha rails,patch,validations railsconf rake rmagick RSA encryption ruby ruby on rails script scrum scrum lessons rails scrumninja shoulda subversion SyncTV TDD testing textmate tips tricks unique hashes unix shell validation view yaml zebra stripes