Exemplo n.º 1
0
        /// <summary>
        /// Finds the root (F(x) = 0) of given function with x between x0 and x1.
        /// </summary>
        /// <param name="f">The function.</param>
        /// <param name="x0">The x0.</param>
        /// <param name="x1">The x1.</param>
        /// <param name="xzero">The x where F(x) = 0.</param>
        /// <param name="xerror">The error (Abs(F(x)).</param>
        /// <returns></returns>
        public static bool FindRoot(NRFindRootFunction f, double x0, double x1,
                                    out double xzero, ref double xerror)
        {
            // Check if there is a root between x0 and x1
            if (f(x0) * f(x1) >= 0)
            {
                xzero  = x0 - 1;
                xerror = double.MaxValue;
                return(false);
            }
            bool   sameError = false;
            double lastError = 0;
            double x2;

            do
            {
                x2 = (x0 * f(x1) - x1 * f(x0)) / (f(x1) - f(x0));
                if (!(Math.Abs(f(x2)) <= xerror))
                {
                    if (f(x0) * f(x2) > 0)
                    {
                        x0 = x1;
                    }
                }
                x1 = x2;
                if (SameValue(lastError, Math.Abs(f(x2))))
                {
                    sameError = true;
                }
                else
                {
                    lastError = Math.Abs(f(x2));
                }
            } while (!sameError && (Math.Abs(f(x2)) > xerror));
            xzero  = x2;
            xerror = Math.Abs(f(x2));
            return(true);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Finds the root (F(x) = 0) of given function with x between x0 and x1.
 /// </summary>
 /// <param name="f">The function.</param>
 /// <param name="x0">The x0.</param>
 /// <param name="x1">The x1.</param>
 /// <param name="xzero">The x where F(x) = 0.</param>
 /// <param name="xerror">The error (Abs(F(x)).</param>
 /// <returns></returns>
 public static bool FindRoot(NRFindRootFunction f, double x0, double x1,
     out double xzero, ref double xerror)
 {
     // Check if there is a root between x0 and x1
       if (f(x0) * f(x1) >= 0)
       {
     xzero = x0 - 1;
     xerror = double.MaxValue;
     return false;
       }
       bool sameError = false;
       double lastError = 0;
       double x2;
       do
       {
     x2 = (x0 * f(x1) - x1 * f(x0)) / (f(x1) - f(x0));
     if (!(Math.Abs(f(x2)) <= xerror))
       if (f(x0) * f(x2) > 0)
     x0 = x1;
     x1 = x2;
     if (SameValue(lastError, Math.Abs(f(x2))))
       sameError = true;
     else
       lastError = Math.Abs(f(x2));
       } while (!sameError && (Math.Abs(f(x2)) > xerror));
       xzero = x2;
       xerror = Math.Abs(f(x2));
       return true;
 }