Method: Minitest::Benchmark#fit_linear

Defined in:
lib/minitest/benchmark.rb

#fit_linear(xs, ys) ⇒ Object

Fits the functional form: a + bx.

Takes x and y values and returns [a, b, r^2].

See: mathworld.wolfram.com/LeastSquaresFitting.html

[View source]

279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/minitest/benchmark.rb', line 279

def fit_linear xs, ys
  n   = xs.size
  xys = xs.zip ys
  sx  = sigma xs
  sy  = sigma ys
  sx2 = sigma(xs)  { |x|   x ** 2 }
  sxy = sigma(xys) { |x, y| x * y  }

  c = n * sx2 - sx**2
  a = (sy * sx2 - sx * sxy) / c
  b = ( n * sxy - sx * sy ) / c

  return a, b, fit_error(xys) { |x| a + b * x }
end