Extreme Optimization > Mathematics Library for .NET > QuickStart Samples > NewtonEquationSolver QuickStart Sample (C#)

Extreme Optimization Mathematics Library for .NET

NewtonEquationSolver QuickStart Sample (C#)

Illustrates the use of the NewtonRaphsonSolver class (Extreme.Mathematics.EquationSolvers namespace) for solving equations and related functions for numerical differentiation (Extreme.Mathematics.Calculus namespace) in C#.

VB.NET code Back to QuickStart Samples

using System;

namespace Extreme.Mathematics.QuickStart.CSharp
{
    // The NewtonRaphsonSolver class resides in the 
    // Extreme.Mathematics.EquationSolvers namespace.
    using Extreme.Mathematics.EquationSolvers;
    // Function delegates reside in the Extreme.Mathematics
    // namespace.
    using Extreme.Mathematics;
    // Special functions reside in the Extreme.Mathematics.SpecialFunctions
    // namespace.
    using Extreme.Mathematics.SpecialFunctions;
    // The NumericalDifferentiator class resides in the
    // Extreme.Mathematics.Calculus namespace.
    using Extreme.Mathematics.Calculus;

    /// <summary>
    /// Illustrates the use of the Newton-Raphson equation solver 
    /// in the Extreme.Mathematics.EquationSolvers namespace of the Extreme
    /// Optimization Mathematics Library for .NET.
    /// </summary>
    class NewtonEquationSolver
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // The Newton-Raphson solver is used to solve 
            // non-linear equations in one variable.
            //
            // The algorithm starts with one starting value,
            // and uses the target function and its derivative
            // to iteratively find a closer approximation to
            // the root of the target function.
            //
            // The properties and methods that give you control
            // over the iteration are shared by all classes
            // that implement iterative algorithms.
            
            //
            // Target function
            //
            // The function we are trying to solve must be
            // provided as a RealFunction. For more
            // information about this delegate, see the
            // FunctionDelegates QuickStart sample.
            RealFunction f = new RealFunction(Math.Sin);
            // The Newton-Raphson method also requires knowledge
            // of the derivative:
            RealFunction df = new RealFunction(Math.Cos);
            // Now let's create the NewtonRaphsonSolver object.
            NewtonRaphsonSolver solver = new NewtonRaphsonSolver();
            // Set the target function and its derivative:
            solver.TargetFunction = f;
            solver.DerivativeOfTargetFunction = df;
            // Set the initial guess:
            solver.InitialGuess = 4;
            // These values can also be passed in a constructor:
            NewtonRaphsonSolver solver2
                = new NewtonRaphsonSolver(f, df, 4);

            Console.WriteLine("Newton-Raphson Solver: sin(x) = 0");
            Console.WriteLine("  Initial guess: 4");
            double result = solver.Solve();
            // The Status property indicates
            // the result of running the algorithm.
            Console.WriteLine("  Result: {0}", solver.Status);
            // The result is also available through the
            // Result property.
            Console.WriteLine("  Solution: {0}", solver.Result);
            // You can find out the estimated error of the result
            // through the EstimatedError property:
            Console.WriteLine("  Estimated error: {0}", solver.EstimatedError);
            Console.WriteLine("  # iterations: {0}", solver.IterationsNeeded);

            //
            // When you don't have the derivative...
            //
            // You can still use this class if you don't have
            // the derivative of the target function. In this
            // case, use the static CreateDelegate method of the
            // NumericalDifferentiator class (Extreme.Mathematics.Calculus
            // namespace) to create a RealFunction
            // that represents the numerical derivative of the
            // target function:
            solver.TargetFunction = f =
                new RealFunction(Bessel.J0);
            solver.DerivativeOfTargetFunction =
                NumericalDifferentiator.CreateDelegate(f);
            solver.InitialGuess = 5;
            Console.WriteLine("Zero of Bessel function near x=5:");
            result = solver.Solve();
            Console.WriteLine("  Result: {0}", 
                solver.Status);
            Console.WriteLine("  Solution: {0}", solver.Result);
            Console.WriteLine("  Estimated error: {0}", 
                solver.EstimatedError);
            Console.WriteLine("  # iterations: {0}", 
                solver.IterationsNeeded);

            //
            // Controlling the process
            //
            Console.WriteLine("Same with modified parameters:");
            // You can set the maximum # of iterations:
            // If the solution cannot be found in time, the
            // Status will return a value of
            // AlgorithmStatus.IterationLimitExceeded
            solver.MaxIterations = 10;
            // You can specify how convergence is to be tested
            // through the ConvergenceCriterion property:
            solver.ConvergenceCriterion = 
                ConvergenceCriterion.WithinRelativeTolerance;
            // And, of course, you can set the absolute or
            // relative tolerance.
            solver.RelativeTolerance = 1e-14;
            // In this example, the absolute tolerance will be 
            // ignored.
            solver.AbsoluteTolerance = 1e-4;
            solver.InitialGuess = 5;
            result = solver.Solve();
            Console.WriteLine("  Result: {0}", solver.Status);
            Console.WriteLine("  Solution: {0}", solver.Result);
            // The estimated error will be less than 5e-14
            Console.WriteLine("  Estimated error: {0}", solver.EstimatedError);
            Console.WriteLine("  # iterations: {0}", solver.IterationsNeeded);
            
            Console.Write("Press Enter key to exit...");
            Console.ReadLine();
        }
    }
}
Overview
Introduction
Features
Documentation
QuickStart Samples
Sample Applications
Downloads
Get it now!
Download trial version
How to Buy
Search

"The Extreme Optimization Statistics Library for .NET is a major boon for those doing statistical work in .NET. I strongly recommend this product."
- Marc Brooks

"I have made it my mission to institutionalize the value of good API design.  I strongly believe that this is key to making developers more productive and happy on our platform. It is clear that you value good API design in your work, and take to heart developer productivity and synergy with the .NET framework."
- Brad Abrams,
Lead Program Manager, Microsoft.

This is a partial list of companies who are using our libraries:
ABB Robotics
Allstate
Applied Materials
Arcam
Astra Schedule
Babson College
Canadian Council on Learning
Canyon Associates
Caxton Associates
CECity
Constellation Energy
CreditSights
DeepOcean
Duke University
Dynamotive
Elecsoft
Engelhard Corporation
Epcor
Equipoise Software
Galileo International
GAM UK
Gammex
GlaxoSmithKline
Global Matrix
The Hartford
Infinera Corporation
Intel
JDS Uniphase
LaBranche & Co.
Learning & Skills Council
Jacobs Consultancy
Litman Gregory
Lucas Systems
Malvern Instruments
Medrio
Merck & Co.
Mintera.
Monitor Software
MorningStar
NanoString Technologies
Paletta Invent
Parametric Portfolio Associates
Prosanos
RATA Associates
RiskShield
Ramboll
Standard & Poor's
Strategic Analysis Corporation
Univ. of Alicante
Univ. of South Carolina
vielife
Xerox
US Army