[R] Finding Zeros of a Function

Hans W Borchers hwborchers at googlemail.com
Fri Oct 8 14:30:02 CEST 2010



Lorenzo Isella wrote:
> 
> Hello,
> And sorry for the late reply.
> You see, my problem is that it is not known a priori whether I have one 
> or two zeros of my function in the interval where I am considering it; 
> on top of that, does BBsolve allow me to select an interval of variation 
> of x?
> Many thanks
> 
> Lorenzo
> 


Let's see how many zeroes are there of the function sin(1/x) in the interval
[0.1, 1.0].  Can you find out by plotting?

In the 1-dimensional case the simplest approach is to split into
subintervals
small enough to contain at most one zero and search each of these, e.g.,
with 
the secant rule --- or uniroot() if you like.

The following function will find 31 zeroes for sin(1/x) using subintervals
of length 1/000, i.e. x <- seq(0.1, 1.0, len=1001); y <- sin(1/x); and call
piecewise(x, y).

Hans Werner

----
piecewise <- function(x, y) {
	n <- length(x)
	zeros <- if (y[1] == 0) c(x[1]) else c()
	for (i in 2:n) {
		if (y[i]*y[i-1] >= 0) {
			if (y[i] == 0) zeros <- c(zeros, x[i])
		} else {
			x0 <- (x[i-1]*y[i] - x[i]*y[i-1])/(y[i] - y[i-1])
			zeros <- c(zeros, x0)
		}
	}
	return(zeros)
}
----

-- 
View this message in context: http://r.789695.n4.nabble.com/Finding-Zeros-of-a-Function-tp2713980p2968228.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list