VB Root Finding Example

← All NMath Code Examples

 

Imports System

Imports CenterSpace.NMath.Core
Imports CenterSpace.NMath.Analysis

Namespace CenterSpace.NMath.Analysis.Examples.VisualBasic

  ' A .NET example in Visual Basic showing how to find a root of a univariate function.
  Module RootFindingExample

    Private Function F(ByVal X As Double) As Double
      Return 4 * Math.Pow(X, 3) + (0.4 * X) - 9
    End Function

    Private Function DF(ByVal x As Double) As Double
      Return 12 * Math.Pow(x, 2) + 0.4
    End Function

    ' The main entry point for the application.
    Sub Main()

      Console.WriteLine()

      Dim D As New Func(Of Double, Double)(AddressOf F)
      Dim Func As New OneVariableFunction(D)

      D = New Func(Of Double, Double)(AddressOf DF)
      Dim Derivative As New OneVariableFunction(D)

      ' Find a root of the function 4x^3 + 0.4x - 9 in the interval
      ' -1000 < x < 1000 using the secant method.
      Dim Finder1 As New SecantRootFinder
      Dim Root As Double = Finder1.Find(Func, -1000, 1000)
      Console.Write("Secant root finder found a root at " & Root)
      Console.WriteLine(" in " & Finder1.Iterations & " iterations.")
      Console.WriteLine()

      ' Function evaluated at the root is within tolerance of zero.
      Console.WriteLine("The function evaluated at the root: " & Func.Evaluate(root))
      Console.WriteLine()

      ' If you know the derivative of the function, you can use the
      ' Newton-Raphson root finder.
      Dim finder2 As New NewtonRaphsonRootFinder
      Root = finder2.Find(Func, Derivative, -1000, 1000)
      Console.Write("Newton-Raphson root finder found the root")
      Console.WriteLine(" in " & finder2.Iterations & " iterations.")
      Console.WriteLine()

      ' Reducing the tolerance speeds up the calculation.
      finder2.Tolerance = 0.1
      Root = finder2.Find(Func, Derivative, -1000, 1000)
      Console.Write("Newton-Raphson root finder found the root")
      Console.WriteLine(" in " & finder2.Iterations & " iterations.")
      Console.WriteLine()

      ' A negative tolerance causes the root finder to run until the maximum
      ' number of iterations is reached.
      finder2.Tolerance = -1
      Root = finder2.Find(Func, Derivative, -1000, 1000)
      Console.Write("Newton-Raphson root finder found the root")
      Console.WriteLine(" in " & finder2.Iterations & " iterations.")
      Console.WriteLine()

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

    End Sub

  End Module

End Namespace


← All NMath Code Examples
Top