# VB Polynomial Least Squares Example

← All NMath Code Examples

```Imports System

Imports CenterSpace.NMath.Core

Namespace CenterSpace.NMath.Examples.VisualBasic

A .NET example in Visual Basic showing how to fit a polynomial through a set of points.
Module PolynomialLeastSquaresExample

Sub Main()

Dim formatString As String = "F3"

Console.WriteLine()

The points: (0.3, -0.9), (0.6, -0.6), (1.8, -13.4), (34.3, -19.3)
Dim X As New DoubleVector(0.3, 0.6, 1.8, 34.3)
Dim Y As New DoubleVector(-0.9, -0.6, -13.4, -19.3)

Fit the best 2nd degree polynomial to the points.
Dim lsq As 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
Dim P As Polynomial = 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")