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:

    Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.
    Anne C. Weisberg (20th century)

    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)