Least Squares Approximation


Description Algorithm

= a minimum

f(a, b) = a + bx

so

Values of a and b can now be computed by taking matrix inverse.

cov(x,y) is the covariance and and are variances.

and a is given in terms of b using

os_num_least_squares class provides the capability to fit a collection of points onto a straight line using least squares approximation techniques. The class has various methods to calculate the scope, intercept, and other statistical quantities of such approximation.

The example code below shows how to use various methods supported by the os_least_squares class.

Example <ospace/math/examples/leastsq.cpp>
#include <ospace/math.h>


int
main()
  {
  os_math_toolkit math_init;

  double vec_data1[ 5 ] = { 1, 2, 1, 3, 4 };
  double vec_data2[ 5 ] = { 3, 1, 3, 5, 8 };

  os_num_vector< double > vec_x( 5 );
  os_num_vector< double > vec_y( 5 );

  for ( int i = 0; i < 5; i++ )
    {
    vec_x[ i ] = vec_data1[ i ];
    vec_y[ i ] = vec_data2[ i ];
    }

  os_least_squares lsq( vec_x, vec_y );

  cout << "x = " << lsq.compute_x( 2 ) << endl;
  cout << "y = " << lsq.compute_y( 2 ) << endl;
  cout << "corr coeff = " << lsq.corr_coeff() << endl;
  cout << "intercept = " << lsq.intercept() << endl;
  cout << "intercept sdev = " << lsq.intercept_sdev() << endl;
  cout << "slope = " << lsq.slope() << endl;
  cout << "slope sdev = " << lsq.slope_sdev() << endl;


  return 0;
  } 

Copyright©1994-2013 Recursion Software LLC
All Rights Reserved - For use by licensed users only.