简体   繁体   中英

R function "uniroot": get some mistake

FX <- function(x)(3/4)*(1-x^2) 
M <- 5000
X2 <- rep(NA,M)
for (i in 1:M) {
   U2 <- runif(1)
   fct <- function(x)FX(x)-U2
   X2[i] <- uniroot(fct,c(-1,1))$root
}

I have tried to do this R-code but I every time I get a mistake saying:

Error in uniroot(fct, c(-1, 1)): f() values at end points not of opposite sign

I don't understand what the problem is and how to fix it.

I don't understand what you're trying to do, but:

When you run uniroot() , the first thing it will do is evaluate the function at the lower and upper end of the interval to see if they are of opposite signs. If they aren't, then there is no guarantee that the function has a root in the interval, and uniroot() won't even try.

The interval you specified is (-1,1) . FX is zero at both ends of the interval, so FX(x) - U2 is equal to -U2 at both ends, so the target will always be negative (between 0 and -1) and both ends.

In principle you can set extendInt = "yes" to have uniroot() widen the interval on which you're looking, but this fails ("no sign change found in 1000 iterations"), probably because the initial interval you specified is symmetric around zero — so that if R tries to widen it by the same amount on both sides, (1-x^2) will always have identical values both ends of the interval, so your test function will also be the same, so it will have the same sign...

Since your function never goes about 3/4, any time your value of U2 is greater than 3/4 (25% of the time,), your target function won't have any real roots...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM