Numerical root finding using Secant Method in c#

By pete rainbow

This class provides a simple method to find the roots of a formula, similar to the GOTO function in Excel

class Secant
    {
         public delegate double Function(double x);

        /// <summary>
        /// gets the root of the supplied formula, wthin a certain precision and iteration cutoff
        /// pass in seed value
        /// </summary>
        /// <param name="prec">how precise an answer we want</param>
        /// <param name="stepsCutoff">max steps</param>
        /// <param name="changePoint">the starting point</param>
        /// <param name="f">the formula</param>
        /// <returns>the value of x if found, nan otherwise</returns>
        public static double Execute( double prec , int stepsCutoff, double changePoint,  Function f )
         {
             double p2, p1, p0;
             int i;
            p0 = f(changePoint);
            p1 = f(changePoint + 1);
            p2 = p1 - f(p1) * (p1 - p0) / (f(p1) - f(p0));

             for (i = 0; System.Math.Abs(p2-p1) > prec && i < stepsCutoff; i++)
            {
                p0 = p1;
                p1 = p2;
                p2 = p1 - f(p1) * (p1 - p0) / (f(p1) - f(p0));
             }
             if (i < stepsCutoff)
                 return p2;
            else
            {
               System.Diagnostics.Debug.WriteLine("{0}.The method did not converge", p2);
                 return double.NaN;
            }
        }

         public static void TestMe()
        {
             double res = Execute(.001, 20, 0, delegate(double x) { return x * x * x - 2 * x - 5; });
            res = Execute(.001, 20, 0, delegate(double x) { return x * x  -4; });
        }
    }

Numerical root finding using Secant Method in c#  (2480 Views)