[R] Finding Zeros of a Function
Hans W Borchers
hwborchers at googlemail.com
Fri Oct 8 14:42:59 CEST 2010
Hans W Borchers wrote:
>
> 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)
> }
> ----
>
Sorry, I meant "how many zeroes are there in the interval [0.01, 1.0] ?" !
The following will find 31 zeroes, and these are all.
x <- seq(0.01, 1.0, len=1001)
y <- sin(1/x);
piecewise(x, y)
Hans Werner
--
View this message in context: http://r.789695.n4.nabble.com/Finding-Zeros-of-a-Function-tp2713980p2968249.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list