Search code examples
rnumerical-integration

Numerical Double Integration in R


I am trying to calculate the value of a double integral numerically in R. My code and the equation that I am trying to code are as follows:

Expectedrsquare<-function(theta=.05,sigma=.0135,alpha=0.05,r0=0,Maturity=20){

library(mvtnorm)

DoubleIntegration<-integrate(function(s) {

sapply(s, function(s) {

  integrate(function(u){

    Mus<- exp(-alpha*s)*r0+(1-exp(-alpha*s))*theta

    Sigmas<-((sigma^2/(2*alpha))*(1-exp(-2*alpha*s)))^0.5

    Muu<- exp(-alpha*u)*r0+(1-exp(-alpha*u))*theta

    Sigmau<-((sigma^2/(2*alpha))*(1-exp(-2*alpha*u)))^0.5

    Cov<-(sigma^2/(2*alpha))*exp(-alpha*(s-u))*(1-exp(-2*alpha*u))

    Chi<-Cov/(Sigmas*Sigmau)

    Zetas<-Mus/Sigmas

    Zetau<-Muu/Sigmau
         Phi2<-pmvnorm(lower=-Inf*c(1,1),upper=c(-Zetas,-Zetau),mean=c(0,0),corr=rbind(c(1,Chi),c(Chi,1)))

    IntegralFunction<-(Mus*Muu+Cov)*(1-pnorm(-Zetas)-pnorm(-Zetau)-Phi2[1])+
      Sigmas*Muu*dnorm(Zetas)*pnorm((Zetau-Chi*Zetas)/((1-Chi^2)^0.5))+
      Sigmau*Mus*dnorm(Zetau)*pnorm((Zetas-Chi*Zetau)/((1-Chi^2)^0.5))+
      Sigmas*Sigmau*(((1-Chi^2)/(2*pi))^0.5)*dnorm(((Zetau^2-2*Chi*Zetas*Zetau+Zetas^2)/((1-Chi^2)))^0.5)

    return(IntegralFunction)

    }, 0, s)$value

  })

}, 0, Maturity)

return(2*DoubleIntegration)
}

Equations

When I compile and run the code I get the following error:

Error in checkmvArgs(lower = lower, upper = upper, mean = mean, corr = corr,  : 
  ‘diag(corr)’ and ‘lower’ are of different length

Can someone please help me with the error or suggest another way of solving the problem.

Thanks.


Solution

  • Finally got this working. Just had to calculate the Bivariate CDF separately in a loop and vectorize it.

    Zetas<-Mus/Sigmas
    Zetau<-Muu/Sigmau
    L<-length(u)
    Phi2<-vector(length=L)
    for(i in 1:L){
         t<-pmvnorm(lower=-Inf*c(1,1),upper=c(-Zetas,-Zetau[i]),mean=c(0,0),
                    corr=rbind(c(1,Chi[i]),c(Chi[i],1)))
          Phi2[i]<-t[1]
        }
    IntegralFunction <- (Mus*Muu+Cov)*(1-pnorm(-Zetas)-pnorm(-Zetau)-Phi2)+
          Sigmas*Muu*dnorm(Zetas)*pnorm((Zetau-Chi*Zetas)/((1-Chi^2)^0.5))+
          Sigmau*Mus*dnorm(Zetau)*pnorm((Zetas-Chi*Zetau)/((1-Chi^2)^0.5))+
          Sigmas*Sigmau*(((1-Chi^2)/(2*pi))^0.5)*
                        dnorm(((Zetau^2-2*Chi*Zetas*Zetau+Zetas^2)/((1-Chi^2)))^0.5)