简体   繁体   中英

Valid upper value of uniroot function in R

I am writing a simple program to compute the inverse of any probability distribution. For example, in the code snippet below I have used the lognormal distribution.

cdf <- function(x){
    plnorm(x, meanlog = 10, sdlog = 1.4, lower.tail = TRUE, log.p = FALSE)
    }

root <- function(q){
    uniroot(function(y){cdf(y)-q},lower=0,upper=Inf,extendInt="no",check.conv=FALSE,tol = .Machine$double.eps^0.25,maxiter = 1000,trace=0)
    }

When I am executing this code and trying to find out the inverse at say probability value root(p), I am getting an error "invalid 'xmax' value".

But when I replace upper=Inf by say upper=100^100 the code is working fine. Please let me know why I cannot use Inf as my upper value.

This is an unfortunate drawback of the uniroot function. You can set upper = .Machine$double.xmax as a substitute for an upper bound of infinity, and this prevents the function from returning an error, but it then has difficulty finding the root, and will often max out the iterations without finding the root of the function. It seems that the method has difficulty finding the root of the function unless you can specify a finite interval where the root is not too far towards one end.

uniroot is a light wrapper around the internal zeroin2 C function, which enforces finitude of the lower and upper arguments (and this makes sense when you think about it--how can you optimize over an infinite interval in finite time?):

https://github.com/SurajGupta/r-source/blob/b28ec999be30efae201f548ed5fb766b5ab9fcb4/src/library/stats/src/optimize.c#L360

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