问题描述
我正在尝试求解R中的一个积分.但是,当我尝试求解该积分时遇到错误.
I am trying to solve an integral in R. However, I am getting an error when I am trying to solve for that integral.
我要求解的方程式如下:
The equation that I am trying to solve is as 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 that I am using is as follows:
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
这是否意味着我无法求解积分?
Does this mean I cannot solve the integral ?
任何解决此问题的方法将受到高度赞赏.
Any possible ways to fix this problem will be highly appreciated.
谢谢.
推荐答案
您可以在try语句中将对Cfun
的调用包装起来
You could wrap the call to Cfun
in a try statement
# 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
值并打印警告,说明集成引发了错误
If you wanted to replace the errors with NA
values and print a warning that the integration threw an 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) }
编辑(facepalm时刻)
出现错误是因为在t=0
时未定义函数(在被积数内除以t).
Edit (facepalm moment)
Your error arises because your function is not defined when t=0
(you divide by t within the integrand).
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) }
这篇关于在R中求解积分给出误差“积分可能是发散的".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!