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

actionmailer ActionView ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factory pattern filemerge find and replace finder fink fixtures fun gem google maps helper helpers imagemagick Intertrust javascript logo math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism prototype.js rails rake rmagick RSA encryption ruby script shoulda subversion SyncTV TDD testing textmate tricks unique hashes unix shell validation view yaml zebra stripes