我正在尝试求解 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
这是否意味着我无法求解积分?
任何可能解决此问题的方法都将受到高度赞赏。
谢谢。
您可以将对
Cfun
的调用包装在 try 语句中
# 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) }