# R code to do bisection search. # For the class Mathematics in Finance # http://www.math.nyu.edu/faculty/goodman/teaching/MathFin/index.html # Author: Jonathan Goodman solver = function( f, # Solve the equation f(x) = y, f is an R function y, # y is the target value a, # seek a solution in the interval [a,b] b, eps){ # return when the uncertainty in x is < eps it_max = 50 # declare failure if you do more than this many iterations famy = f(a) - y # famy is for "f(a) minus y" fbmy = f(b) - y # find (x) so that f(x) - y = 0 # stop if f does not change sign between a and b it = 0 # the number of iterations done so far while ( (b-a) > eps ){ c = (a+b)*.5 fcmy = f(c) - y # Evaluate f at the midpoint of the interval if ( famy*fcmy < 0){ # f changes sign between a and c, ... b = c # ... so the new interval is [a,c] fbmy = fcmy } else{ # f changes sign between c and b, ... a = c # ... so the new interval is [c,b] famy = fcmy } cat("a is ", a, ", b is ", b, " famy is ", famy, ", fbmy is ", fbmy, "\n") it = it + 1 # just finished another iteration if ( it > it_max){ # Please, please don't let this be an infinite loop! stop("solver stopping because it did too many iterations\n") } } return(a) }