我正在尝试解决R中的积分。但是,当我试图解决该积分时,我收到错误。
我想解决的等式如下:
$$ C_m = \frac{{abs{x}}e^{2x}}{\pi^{1/2}}\int_0^t t^{-3/2}e^{-x^2/t-t}dt $$
我使用的代码如下:
a <- seq(from=-10, by=0.5,length=100)
## Create a function to 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)
我得到的错误如下:
Error in integrate(integrand, lower = 0, upper = upper) :
the integral is probably divergent
这是否意味着我无法解决积分?
任何可能解决此问题的方法都将受到高度赞赏。
感谢。
答案 0 :(得分:1)
您可以在try语句中将调用包装到Cfun
# note using `lapply` so errors don't coerce the result to character
b <- lapply(a, function(x,...) try(Cfun(x, ...), silent = TRUE), upper = 1)
如果您想用NA
值替换错误并打印警告集成引发错误
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) }
出现错误是因为t=0
(在被积函数中除以t)时未定义函数。
Cfun <- function(XX, upper){
integrand <- function(x)x^(-1.5)*exp((-XX^2/x)-x)
# deal with xx=0
if(isTRUE(all.equal(XX, 0)){
warning('The integrand is not defined at XX = 0')
return(NA_real_)
}
# deal with 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) }