“non-finite function value” when using integrate() in R

前端 未结 1 680
感动是毒
感动是毒 2021-01-14 12:59

I am using the following R code, taken from a published paper (citation below). This is the code:

int2=function(x,r,n,p) {
    (1+x)^((n-1-p)/2)*(1+(1-r^2)*         


        
相关标签:
1条回答
  • 2021-01-14 13:45

    The issue is that your integral function is generating NaN values when called with x values in its domain. You're integrating from 0 to Infinity, so let's check a valid x value of 1000:

    int2(1000, sqrt(0.245), 530, 3)
    # [1] NaN
    

    Your objective multiplies four pieces:

    x <- 1000
    r <- sqrt(0.245)
    n <- 530
    p <- 3
    (1+x)^((n-1-p)/2)
    # [1] Inf
    (1+(1-r^2)*x)^(-(n-1)/2)
    # [1] 0
    x^(-3/2)
    # [1] 3.162278e-05
    exp(-n/(2*x))
    # [1] 0.7672059
    

    We can now see that the issue is that you're multiplying infinity by 0 (or rather something numerically equal to infinity times something numerically equal to 0), which is causing the numerical issues. Instead of calculating a*b*c*d, it will be more stable to calculate exp(log(a) + log(b) + log(c) + log(d)) (using the identity that log(a*b*c*d) = log(a)+log(b)+log(c)+log(d)). One other quick note -- the value x=0 needs a special case.

    int3 = function(x, r, n, p) {
      loga <- ((n-1-p)/2) * log(1+x)
      logb <- (-(n-1)/2) * log(1+(1-r^2)*x)
      logc <- -3/2 * log(x)
      logd <- -n/(2*x)
      return(ifelse(x == 0, 0, exp(loga + logb + logc + logd)))
    }
    integrate(f=int3,lower=0,upper=Inf,n=530,r=sqrt(.245),p=3, stop.on.error=FALSE)
    # 1.553185e+27 with absolute error < 2.6e+18
    
    0 讨论(0)
提交回复
热议问题