// Barlow and Barnett, Computing for Scientists 1998 // page 221 C++ and Fortran 90 // Update to new ANSI standard by Jim Crumley 20130225 // example of Least squares code #include #include using namespace std; int LeastSquares(double x[ ] , double y[ ] , double sig , int n); double var_p(double p[ ] , double *p_bar , int n); double covxy(double p[ ] , double q[ ] , double p_bar , double q_bar , int n); // the prototypes int LeastSquares(double x[ ] , double y[ ] , double sig , int n) //==least-squares calculation data in arrays x[n] , y[n] , error in sig { //==========carry out checks for n > 2 , sig > 0.0 , etc double x_bar , y_bar , var_x , var_y , cov_xy , a , b ; var_x = var_p(x , &x_bar , n); var_y = var_p(y , &y_bar , n); cov_xy = covxy(x , y , x_bar , y_bar , n); b = cov_xy / var_x; a = y_bar - b*x_bar; double chisq = 0.0; for (int k=0; k 2.1) cout << " Check data, fit is bad. Chisq = " << chisq << endl; //=======output results ... cout << "\n intercept a = " << a << endl; cout << " slope b = " << b << endl; //=======output other details and graph the results. Plot residuals ! return 0; } double var_p(double p[ ] , double *p_bar , int n) { //=======find variance of vector : updating variance & mean *p_bar = p[0] ; double varp = 0.0; for (int k=1; k