4d monte carlo 集成 R

4d monte carlo integration R

如何使用Monte Carlo方法整合函数

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

哪个取决于 4 个维度的 4 个变量?

我是说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]

更新 函数是

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]))
}

我想整合它

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

由于您的积分表达式的特殊结构,您可以将嵌套积分重写为积分的乘积。

因此,下面的解决方案可能是您的示例(随机种子 set.seed(1)):

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))))

这样

> res1
[1] 0.01559343

嵌套积分:你需要先重写你的函数f,即

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

这样

> res2
[1] 0.01559343