Implementation and Analysis of Least-Squares Estimation

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.

Example 13.2. Implementation of Least-Squares Estimation
/***************************************************************************** * * * -------------------------------- 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. ...

Get Mastering Algorithms with C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.