integration - Solving an integral in R gives error "The integral is probably divergent" -
i trying solve integral in r. however, getting error when trying solve integral.
the equation trying solve follows:
$$ c_m = \frac{{abs{x}}e^{2x}}{\pi^{1/2}}\int_0^t t^{-3/2}e^{-x^2/t-t}dt $$
the code using follows:
a <- seq(from=-10, by=0.5,length=100) ## create function compute integration cfun <- function(xx, upper){ integrand <- function(x)x^(-1.5)*exp((-xx^2/x)-x) integrated <- integrate(integrand, lower=0, upper=upper)$value (final <- abs(xx)*pi^(-0.5)*exp(2*xx)*integrated) } b<- sapply(a, cfun, upper=1)
the error getting follows:
error in integrate(integrand, lower = 0, upper = upper) : integral divergent
does mean cannot solve integral ?
any possible ways fix problem highly appreciated.
thanks.
you wrap call cfun
in try statement
# note using `lapply` errors don't coerce result character b <- lapply(a, function(x,...) try(cfun(x, ...), silent = true), upper = 1)
if wanted replace errors na
values , print warning integration threw error
cfun <- function(xx, upper){ integrand <- function(x)x^(-1.5)*exp((-xx^2/x)-x) int <- try(integrate(integrand, lower=0, upper=upper), silent = true) if(inherits(int ,'try-error')){ warning(as.vector(int)) integrated <- na_real_ } else { integrated <- int$value } (final <- abs(xx)*pi^(-0.5)*exp(2*xx)*integrated) }
edit (facepalm moment)
your error arises because function not defined when t=0
(you divide t within integrand).
cfun <- function(xx, upper){ integrand <- function(x)x^(-1.5)*exp((-xx^2/x)-x) # deal xx=0 if(istrue(all.equal(xx, 0)){ warning('the integrand not defined @ xx = 0') return(na_real_) } # deal other integration errors int <- try(integrate(integrand, lower=0, upper=upper), silent = true) if(inherits(int ,'try-error')){ warning(as.vector(int)) integrated <- na_real_ } else { integrated <- int$value } (final <- abs(xx)*pi^(-0.5)*exp(2*xx)*integrated) }
Comments
Post a Comment