**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 r_{i} = y_{i} - yHat_{i}.

● ResidualSumOfSquares gets
the residual sum of squares (y_{0 }- yHat_{0})^{2} + (y_{1} - yHat_{1})^{2} + ... + (y_{m-1} - yHat_{m-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)