Search code examples
rintegrationmontecarlo

4d monte carlo integration R


How to integrate function using the Monte Carlo method

F(X[1],X[2],X[3],X[4])

Which depends on 4 variable by 4 dimensions?

I mean int_{0}^{1} int_{0}^{1} int_{0}^{1} int_{0}^{1} X[1]X[2]X[3]X[4] dX[1] dX[2] dX[3] dX[4]

UPD function is

data1 =  rnorm(100, 0, 1)
data2 =  rnorm(100, 0.1, 0.5)
data3 =  rnorm(100, 0.2, 0.8)
data4 =  rnorm(100, 0.3, 0.9)

kernel1 = kdensity(data1,kernel = 'gaussian')
kernel2 = kdensity(data2,kernel = 'gaussian')
kernel3 = kdensity(data3,kernel = 'gaussian')
kernel4 = kdensity(data4,kernel = 'gaussian')


f <- function(X) {
  return(X[1]*kernel1(X[1])*kernel2(X[2])*kernel3(X[3])*kernel4(X[4]))
}

and i want to integrate it

int_{0}^{1} int_{0}^{1} int_{0}^{1} int_{0}^{1} f dX[1] dX[2] dX[3] dX[4]


Solution

  • Due to your particular structure of integral expression, you can rewrite your nested integral into a product of integrals.

    Thus, the solution below may be a example (with random seed set.seed(1)) for you:

    g <- Vectorize(function(ker) {integrate(ker,0,1)}$value)
    gE <- function(ker) {integrate(function(x) x*ker(x),0,1)}$value
    res1 <- prod(c(gE(kernel1),g(c(kernel2,kernel3,kernel4))))
    

    such that

    > res1
    [1] 0.01559343
    

    Nested Integral: you need to rewrite your function f first, i.e.,

    f <- function(x1,x2,x3,x4) {
      return(x1*kernel1(x1)*kernel2(x2)*kernel3(x3)*kernel4(x4))
    }
    
    res2 <- integrate(Vectorize(function(x4) 
      integrate(Vectorize(function(x3,x4) 
        integrate(Vectorize(function(x2,x3,x4) 
          integrate(f,0,1,x2,x3,x4)$value),
          0,
          1,
          x3,
          x4)$value),
        0,
        1,
        x4)$value),
      0,
      1)$value
    

    such that

    > res2
    [1] 0.01559343