[R] Is there a bisection method in R?

Ravi Varadhan rvaradhan at jhmi.edu
Fri Sep 17 23:44:42 CEST 2010


Here is something simple (does not have any checks for bad input), yet
should be adequate:

bisect <- function(fn, lower, upper, tol=1.e-07, ...) {
f.lo <- fn(lower, ...) 
f.hi <- fn(upper, ...) 
feval <- 2

if (f.lo * f.hi > 0) stop("Root is not bracketed in the specified interval
\n")
chg <- upper - lower

while (abs(chg) > tol) {
	x.new <- (lower + upper) / 2
	f.new <- fn(x.new, ...)
	if (abs(f.new) <= tol) break
	if (f.lo * f.new < 0) upper <- x.new 
	if (f.hi * f.new < 0) lower <- x.new 
	chg <- upper - lower
	feval <- feval + 1
}
list(x = x.new, value = f.new, fevals=feval)
}

# An example
fn1 <- function(x, a) {
exp(-x) - a*x 
}

bisect(fn1, 0, 2, a=1)
 
bisect(fn1, 0, 2, a=2)


Ravi.

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Peter Dalgaard
Sent: Friday, September 17, 2010 4:16 PM
To: Gregory Gentlemen
Cc: r-help at r-project.org
Subject: Re: [R] Is there a bisection method in R?

On 09/17/2010 09:28 PM, Gregory Gentlemen wrote:
> If uniroot is not a bisection method, then what function in R does use
bisection?
> 

Why do you assume that there is one? uniroot contains a better algorithm
for finding bracketed roots.

It shouldn't be too hard to roll your own if you need one for
pedagogical purposes.

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list