0

我正在尝试求解 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

这是否意味着我无法求解积分?

任何可能解决此问题的方法都将受到高度赞赏。

谢谢。

4

1 回答 1

2

您可以将调用包装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) }
于 2013-04-09T03:42:02.433 回答