fitThroughOrigin function

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

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

Implementation

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

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

  double mxy = 0.0;
  double mxx = 0.0;
  for (int i = 0; i < x.length; i++) {
    mxx += x[i] * x[i];
    mxy += x[i] * y[i];
  }

  return mxy / mxx;
}