当上限为Inf时,R中的积分失败

时间:2017-07-25 20:53:05

标签: r integrate

我需要在数值上近似两个对数正态随机变量之和的对数方差。我想在R中这样做,这是一个例子:

################
## Setup data ##
################

sdX1 = 0.33
sdX2 = 0.70
muX1 = log(32765) - 0.5 * sdX1^2
muX2 = log(52650) - 0.5 * sdX2^2

####################################
## PDF for sum of 2 lognormal RVs ##
####################################

d2lnorm = function(z, muX1, muX2, sdX1, sdX2){

    #PDFs
    L1 = distr::Lnorm(meanlog = muX1, sdlog = sdX1)
    L2 = distr::Lnorm(meanlog = muX2, sdlog = sdX2)

    #Convlution integral
    L1plusL2 = distr::convpow(L1 + L2, 1)

    #Density function
    f.Z = distr::d(L1plusL2)

    #Evaluate
    return(f.Z(z))

}

############################################
## Expectation for sum of 2 lognormal RVs ##
############################################    

ex2lnorm = function(muX1, muX2, sdX1, sdX2){    

    #E(g(x)) = integral of g(x) * f(x) w.r.t x
    integrate(function(z) log(z) * d2lnorm(z, muX1 = muX1, muX2 = muX2, sdX1 = sdX1, sdX2 = sdX2), lower = 0, upper = +Inf)$value

}

##############
## Run code ##
##############

ex2lnorm(muX1, muX2, sdX1, sdX2)

但是,积分的计算结果为0.如果我将integrate的上限更改为大数,则可以正常工作。但是,我正在运行一系列模拟,而且我无法通过上限来使其每次都能正常工作。是否还有其他方法可以让它始终如一地运作?

1 个答案:

答案 0 :(得分:1)

如果找到不给出0的最大上限值,您可以做什么:

ex2lnorm = function(muX1, muX2, sdX1, sdX2){    

  f <- function(z) log(z) * d2lnorm(z, muX1 = muX1, muX2 = muX2, sdX1 = sdX1, sdX2 = sdX2)

  upper <- 2^10
  cond.lower <- FALSE
  repeat {
    new <- integrate(f, lower = 0, upper = upper)$value
    if (new > 0) cond.lower <- TRUE
    if (cond.lower && new == 0) break
    upper <- upper * 2
    prev <- new
  }

  prev
}