The implementation of least-squares estimation presented
here requires us to do little more than compute a few summations and
apply the results to the formulas presented earlier. The operation
begins by summing all values for xi
in sumx
, all values for
yi in
sumy
, all values of
xi
2 in sumx2
, and all values of
xi yi
in sumxy
(see Example 13-2). Once we have completed
this, we compute b 1 and
b 0 using the formulas
presented earlier.
The runtime complexity of lsqe is O (n), where n is the number of points used to determine b 1 and b 0. This is because a single loop that iterates n times is used to compute the summations.
/***************************************************************************** * * * -------------------------------- lsqe.c -------------------------------- * * * *****************************************************************************/ #include <math.h> #include "nummeths.h" /***************************************************************************** * * * --------------------------------- lsqe --------------------------------- * * * *****************************************************************************/ void lsqe(const double *x, const double *y, int n, double *b1, double *b0) { double sumx, sumy, sumx2, sumxy; int i; /***************************************************************************** * * * Compute the required summations. * * * *****************************************************************************/ sumx = 0.0; sumy = 0.0; sumx2 = 0.0; sumxy = 0.0; for (i = 0; i < n; i++) { sumx = sumx + x[i]; sumy = sumy + y[i]; sumx2 = sumx2 + pow(x[i], 2.0); sumxy = sumxy + (x[i] * y[i]); } /***************************************************************************** * * * Compute the least-squares estimators. * * * *****************************************************************************/ *b1 = (sumxy - ((sumx * sumy)/(double)n)) / (sumx2-(pow(sumx,2.0)/(double)n)); *b0 = (sumy - ((*b1) * sumx)) / (double)n; return; }