如何为以下Bisection Method代码设置最大迭代次数= 20?我应该只使用feval还是别的什么?
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)
}
答案 0 :(得分:2)
将while
中的条件更改为while (abs(diff) > tol & feval<22)
。 22因为在第一次迭代中feval
已经是2。