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:

    ...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.
    Ellen Glasgow (1873–1945)

    Motion or change, and identity or rest, are the first and second secrets of nature: Motion and Rest. The whole code of her laws may be written on the thumbnail, or the signet of a ring.
    Ralph Waldo Emerson (1803–1882)