Question

How can I set a maximum iteration = 20 for the following Bisection Method code? Should I work on feval only or something else?

rf.bisection <- function(f, lower, upper, tol=1e-4) { 
flow <- f(lower) 
fupper <- f(upper) 
feval <- 2 

if (flow * fupper > 0) stop("The given interval does not contain the root!
\n") 
diff <- upper - lower 

while (abs(diff) > tol) { 
    newpoint <- (lower + upper) / 2 
    newf <- f(newpoint) 
    if (abs(newf) <= tol) break 
    if (flow * newf < 0) upper <- newpoint 
    if (fupper * newf < 0) lower <- newpoint 
    diff <- upper - lower 
    feval <- feval + 1 
} 
list(x = newx, value = newf, fevals=feval) 
} 
Était-ce utile?

La solution

Change your condition in while to while (abs(diff) > tol & feval<22). 22 because in first iteration feval is already 2.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top