C#, code Haishibei (44) - the C# source code of "Newton's method" for "a real root of a nonlinear equation"

 

using System;

namespace Zhou.CSharp.Algorithm
{
    public delegate double delFunction_x(double x);
    public delegate double delFunction_xa(double[] x);
    public delegate double delFunction_x_y(double x, double y);
    public delegate double delFunction_x_ya(double x, double[] y);
    public delegate double delFunction_xa_ya(double[] x, double[] y);

    /// <summary>
    /// Class NLEquations for solving nonlinear equations
    /// Zhou Changfa
    /// Adapted to deep confusion
    /// </summary>
    public static partial class NLEquations
    {

        /// <summary>
        /// Newton's method for finding a real root of a nonlinear equation
        /// Calculation of the function f(x) at the left end of the equation and its first derivative f'(x)
        /// void Func(double x, double[] y)
        /// y(0) returns the value of f(x)
        /// y(1) returns the value of f'(x)
        /// </summary>
        /// <param name="Func ">Function to calculate the left end of the equation</param>
        /// <param name="x">Input the initial value of the iteration (guess the solution) and return a real root found in the interval</param>
        /// <param name ="nMaxIt">Number of recursions</param>
        /// <param name="eps">Precision control parameters</param>
        /// <return>Bool type, whether the solution is successful</return>
        public static bool GetRootNewton( delFunction_x_ya Func, ref double x, int nMaxIt,double eps)
        {             int r;             double d, p, x0, x1 = 0.0;


            double[] y = new double[2];

            // Condition value
            r = nMaxIt;
            x0 = x;
            Func(x0, y);

            // load, load
            d = eps + 1.0;
            while ( ( d >= eps ) && ( r ! = 0 ))
            {                 if ( Math . Abs ( y [ 1 ] ) < float . Epsilon )                 {                     return false ;                 }                 x1 = x0 - y[0] / y[1];                 Func ( x1 , y ) ;





                d = Math.Abs(x1 - x0);
                p = Math.Abs(y[0]);
                if (p > d)
                {
                    d = p;
                }
                x0 = x1;
                r = r - 1;
            }

            x = x1;

            return true;
        }
}

}

Guess you like

Origin blog.csdn.net/beijinghorn/article/details/131133602