Brent's Method - Example Code

Example Code

The above algorithm can be translated to c-like code as follows:

public static double BrentsMethodSolve(Func function, double lowerLimit, double upperLimit, double errorTol) { double a = lowerLimit; double b = upperLimit; double c = 0; double d = double.MaxValue; double fa = function(a); double fb = function(b); double fc = 0; double s = 0; double fs = 0; // if f(a) f(b) >= 0 then error-exit if (fa * fb >= 0) { if (fa < fb) return a; else return b; } // if |f(a)| < |f(b)| then swap (a,b) end if if (Math.Abs(fa) < Math.Abs(fb)) { double tmp = a; a = b; b = tmp; tmp = fa; fa = fb; fb = tmp; } c = a; fc = fa; bool mflag = true; int i = 0; while (!(fb==0) && (Math.Abs(a-b) > errorTol)) { if ((fa != fc) && (fb != fc)) // Inverse quadratic interpolation s = a * fb * fc / (fa - fb) / (fa - fc) + b * fa * fc / (fb - fa) / (fb - fc) + c * fa * fb / (fc - fa) / (fc - fb); else // Secant Rule s = b - fb * (b - a) / (fb - fa); double tmp2 = (3 * a + b) / 4; if ((!(((s > tmp2) && (s < b)) || ((s < tmp2) && (s > b)))) || (mflag && (Math.Abs(s - b) >= (Math.Abs(b - c) / 2))) || (!mflag && (Math.Abs(s - b) >= (Math.Abs(c - d) / 2)))) { s = (a + b) / 2; mflag = true; } else { if ((mflag && (Math.Abs(b - c) < errorTol)) || (!mflag && (Math.Abs(c - d) < errorTol))) { s = (a + b) / 2; mflag = true; } else mflag = false; } fs = function(s); d = c; c = b; fc = fb; if (fa * fs < 0) { b = s; fb = fs; } else { a = s; fa = fs; } // if |f(a)| < |f(b)| then swap (a,b) end if if (Math.Abs(fa) < Math.Abs(fb)) { double tmp = a; a = b; b = tmp; tmp = fa; fa = fb; fb = tmp; } i++; if (i > 1000) throw new Exception(String.Format("Error is {0}", fb)); } return b; }

Read more about this topic:  Brent's Method

Famous quotes containing the word code:

    Faultless honesty is a sine qua non of business life. Not alone the honesty according to the moral code and the Bible. When I speak of honesty I refer to the small, hidden, evasive meannesses of our natures. I speak of the honesty of ourselves to ourselves.
    Alice Foote MacDougall (1867–1945)

    Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a “sock” in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.
    George Bernard Shaw (1856–1950)