fit function

Tuple2<double, double> fit(
  1. List<double> x,
  2. List<double> y
)

Least-Squares fitting the points (x,y) to a line y : x -> a+b*x, returning its best fitting parameters as (a, b) tuple, where a is the intercept and b the slope.

Implementation

Tuple2<double, double> fit(List<double> x, List<double> y) {
  if (x.length != y.length) {
    throw ArgumentError(messages.sampleVectorsSameLength);
  }

  if (x.length <= 1) {
    throw ArgumentError(messages.regressionNotEnoughSamples);
  }

  // First Pass: Mean (Less robust but faster than ArrayStatistics.Mean)
  double mx = 0.0;
  double my = 0.0;
  for (int i = 0; i < x.length; i++) {
    mx += x[i];
    my += y[i];
  }

  mx /= x.length;
  my /= y.length;

  // Second Pass: Covariance/Variance
  double covariance = 0.0;
  double variance = 0.0;
  for (int i = 0; i < x.length; i++) {
    double diff = x[i] - mx;
    covariance += diff * (y[i] - my);
    variance += diff * diff;
  }

  var b = covariance / variance;
  return Tuple2<double, double>(my - b * mx, b);
}