# C# Polynomial Least Squares Example

← All NMath Code Examples

```using System;
using System.Globalization;

using CenterSpace.NMath.Core;
using CenterSpace.NMath.Analysis;

namespace CenterSpace.NMath.Analysis.Examples.CSharp
{
class PolynomialLeastSquaresExample
{
/// <summary>
/// A .NET example in C# showing how to fit a polynomial through a set of points
/// while minimizing the least squares of the residuals.
/// </summary>
static void Main( string[] args )
{
var formatString = "F3";

Console.WriteLine();

// The points: (0.3, -0.9), (0.6, -0.6), (1.8, -13.4), (34.3, -19.3)
var x = new DoubleVector( 0.3, 0.6, 1.8, 34.3 );
var y = new DoubleVector( -0.9, -0.6, -13.4, -19.3 );

// Fit the best 2nd degree polynomial to the points using the
// polynomial fitter, PolynomialLeastSquares.
var lsq = new PolynomialLeastSquares( 2, x, y );
Console.WriteLine( "Best polynomial of degree " + lsq.Degree + " is: " );
Console.WriteLine();
Console.WriteLine( lsq.FittedPolynomial.ToString( formatString ) );
Console.WriteLine();
Console.WriteLine( "residual sum of squares: " + lsq.LeastSquaresSolution.ResidualSumOfSquares.ToString( "E3" ) );
Console.WriteLine();
Console.WriteLine();

// Fit the best 3rd degree polynomial to the points.
lsq = new PolynomialLeastSquares( 3, x, y );
Console.WriteLine( "Best polynomial of degree " + lsq.Degree + " is: " );
Console.WriteLine();
Console.WriteLine( lsq.FittedPolynomial.ToString( formatString ) );
Console.WriteLine();
Console.WriteLine( "residual sum of squares: " + lsq.LeastSquaresSolution.ResidualSumOfSquares );
Console.WriteLine();
Console.WriteLine();

// Fit the best 4th degree polynomial to the points.
lsq = new PolynomialLeastSquares( 4, x, y );
Console.WriteLine( "Best polynomial of degree " + lsq.Degree + " is: " );
Console.WriteLine();
Console.WriteLine( lsq.FittedPolynomial.ToString( formatString ) );
Console.WriteLine();
Console.WriteLine( "residual sum of squares: " + lsq.LeastSquaresSolution.ResidualSumOfSquares.ToString( "E3" ) );
Console.WriteLine();

// Evaluate the polynomial
Polynomial p = lsq.FittedPolynomial;
Console.WriteLine( "Polynomial evaluated at 4.5: " + p.Evaluate( 4.5 ).ToString( formatString ) );
Console.WriteLine();

// First derivative
Console.WriteLine( "Derivative of the polynomial: " );
Console.WriteLine( p.Derivative().ToString( formatString ) );
Console.WriteLine();

// Second derivative
Console.WriteLine( "Second Derivative of the polynomial: " );
Console.WriteLine( p.Derivative().Derivative().ToString( formatString ) );
Console.WriteLine();

// Integrate
Console.WriteLine( "Integral of the polynomial from 3.2 to 4.6:" );
Console.WriteLine( p.Integrate( 3.2, 4.6 ).ToString( formatString ) );

Console.WriteLine();
Console.WriteLine( "Press Enter Key" );