两种数值积分方法有两种不同的结果?

时间:2019-02-19 12:10:57

标签: r gaussian numerical-methods

我计算了高斯密度与某些函数乘积的积分。

首先,我使用功能int2()rmutil包)来完成此操作。 然后,我用高斯-赫尔姆特点做到了。 我获得的两个结果是不同的。 我是否应该认为高斯-赫尔米特方法是好的方法,而数值积分是一个近似值?

我在下面提供一个示例:

1。 rmutil :: int2()

library(rmutil)

Sig <- matrix (c(0.2^2, 0, 0, 0.8^2), ncol=2)
Mu<- c(2, 0) 


to.integrate <- function(B0, B1) {
  first.int= 1/0.8 * (1.2 * exp(B0 + B1 * 0.5))^(-1/0.8) * gamma(1/0.8) 
  B=matrix(c(B0, B1), ncol=1)
  multi.norm=1 / (2 * pi * det(Sig)^(1/2)) * 
    exp (- 0.5 * t( B - Mu ) %*% solve(Sig) %*%( B - Mu ) )
  return (first.int %*% multi.norm)
}

result_int2 <- int2(to.integrate, a=c(-Inf, -Inf), b=c(Inf, Inf), 
                     eps=1.0e-6, max=16, d=5)

2。计算多元高斯正交点:

library(statmod)
mgauss.hermite <- function(n, mu, sigma) {
  dm  <- length(mu)
  gh  <- gauss.quad(n, 'hermite')
  gh  <- cbind(gh$nodes, gh$weights)
  idx <- as.matrix(expand.grid(rep(list(1:n), dm)))
  pts <- matrix(gh[idx, 1], nrow(idx), dm)
  wts <- apply(matrix(gh[idx, 2], nrow(idx), dm), 1, prod)
  eig <- eigen(sigma) 
  rot <- eig$vectors %*% diag(sqrt(eig$values))
  pts <- t(rot %*% t(pts) + mu)
  return(list(points=pts, weights=wts))
}

nod_wei <- mgauss.hermite(10, mu=Mu, sigma=Sig)
gfun <- function(B0, B1) {
  first.int <- 1/0.8 *(1.2 * exp(B0 + B1 * 0.5))^(-1/0.8)* gamma(1/0.8) 
  return(first.int)
}

result_GH <- sum(gfun(nod_wei$points[, 1], nod_wei$points[, 2]) * nod_wei$weights)/pi

result_int2
result_GH

1 个答案:

答案 0 :(得分:0)

错误来自于mgauss.hermite函数中点的计算方式。

我将Cholesky分解的Sigma矩阵分解改为乘以2的平方根。 两种方法的结果非常相似。 以下是mgauss.hermite函数的更正

mgauss.hermite <- function(n, mu, sigma) {
  dm  <- length(mu)
  gh  <- gauss.quad(n, 'hermite')
  gh  <- cbind(gh$nodes, gh$weights)
  idx <- as.matrix(expand.grid(rep(list(1:n),dm)))
  pts <- matrix(gh[idx,1],nrow(idx),dm)
  wts <- apply(matrix(gh[idx,2],nrow(idx),dm), 1, prod)
  rot <- 2.0**0.5*t(chol(sigma))
  pts <- t(rot %*% t(pts) + mu)
  return(list(points=pts, weights=wts))
}