C# Root Finding Example

← All NMath Code Examples

 

using System;

using CenterSpace.NMath.Core;


namespace CenterSpace.NMath.Examples.CSharp
{
  class RootFindingExample
  {
    /// <summary>
    /// A .NET example in C# showing how to find a root of a univariate function
    /// using the secant and Newton-Raphson methods.
    /// </summary>
    static void Main( string[] args )
    {
      Console.WriteLine();

      // Find a root of the function 4x^3 + 0.4x - 9 in the interval
      // -1000 < x < 1000 using the secant method.
      var finder1 = new SecantRootFinder();
      double root = finder1.Find( function, -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: " + function.Evaluate( root ) );
      Console.WriteLine();

      // If you know the derivative of the function, you can use the
      // Newton-Raphson root finder.
      var finder2 = new NewtonRaphsonRootFinder();
      root = finder2.Find( function, 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( function, 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( function, 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();
    }

    private static OneVariableFunction function = new OneVariableFunction( new Func<double, double>( F ) );

    private static OneVariableFunction derivative = new OneVariableFunction( new Func<double, double>( DF ) );

    private static double F( double x )
    {
      return 4 * Math.Pow( x, 3 ) + ( 0.4 * x ) - 9;
    }

    private static double DF( double x )
    {
      return 12 * Math.Pow( x, 2 ) + 0.4;
    }

  } // class

} // namespace



← All NMath Code Examples
Top