NMath User's Guide

TOC | Previous | Next | Index

8.3 Using Least Squares Solutions (.NET, C#, CSharp, VB, Visual Basic, F#)

Once constructed, an NMath least squares class provides read-only properties to access the least squares solution to the linear system Ax = y:

X gets the least squares solution.

Yhat gets the predicted value yHat = Ax, where x is the calculated solution.

Residuals gets the vector of residuals r where ri = yi - yHati.

ResidualSumOfSquares gets the residual sum of squares (y0 - yHat0)2 + (y1 - yHat1)2 + ... + (ym-1 - yHatm-1)2.

Rank gets the effective rank of the matrix A.

Tolerance gets the tolerance used to compute the effective rank of the matrix A.

For instance, this code calculates the slope and intercept of a linear least squares fit through five data points, then prints out the properties of the solution:

Code Example – C# least squares

var A = new DoubleMatrix( "5x1[20.0  30.0  40.0  50.0  60.0]" );
var y = new DoubleVector( "[.446 .601 .786 .928 .950]" );
var lsq = new DoubleLeastSquares( A, y, true );



Console.WriteLine( "Y-intercpt = {0}", lsq.X[0] );
Console.WriteLine( "Slope = {0}", lsq.X[1] );
Console.WriteLine( "Residuals = {0}", lsq.Residuals );
Console.WriteLine( "Residual Sum of Squares (RSS) = {0}", 
   lsq.ResidualSumOfSquares );

Code Example – VB least squares

Dim A As New DoubleMatrix("5x1[20.0  30.0  40.0  50.0  60.0]")
Dim Y As New DoubleVector("[.446 .601 .786 .928 .950]")
Dim LSQ As New DoubleLeastSquares(A, Y, True)



Console.WriteLine("Y-intercpt = {0}", LSQ.X(0))
Console.WriteLine("Slope = {0}", LSQ.X(1))
Console.WriteLine("Residuals = {0}", LSQ.Residuals)
Console.WriteLine("Residual Sum of Squares (RSS) = {0}", 
  LSQ.ResidualSumOfSquares)

Top

Top