r - 使用 hcubature 在 R 中集成
问题描述
rho <- 0.2
f1 <- function(X) {
x <- X[1]
y <- X[2]
(pnorm(x-10)-pnorm(y-10))^2*(exp(-((x-10)^2-2*rho*(x-10)*(y-10)+(y-10)^2)/(2*(1-rho^2)))/(2*pi*sqrt(1-rho^2)))
}
library(cubature)
round(hcubature(f1, c(-Inf, -Inf), c(Inf, Inf), tol = 1e-12)$integral, 6)
这给出了 0,但正确答案应该是 0.1348。有人可以帮我吗?非常感谢。
解决方案
这个问题对于任何数值积分方法都是常见的:如果你没有在正确的地方评估函数,它就会看起来是恒定的。您的关节密度以 附近为中心c(10, 10)
,并且该hcubature
函数主要在其非常低的位置附近对其进行评估c(0, 0)
,因此它看起来恒定,接近 0。您可以看到如下:
rho <- 0.2
# First, plot the density function
fn <- function(x, y) (pnorm(x-10)-pnorm(y-10))^2*(exp(-((x-10)^2-2*rho*(x-10)*(y-10)+(y-10)^2)/(2*(1-rho^2)))/(2*pi*sqrt(1-rho^2)))
# Record the points used by hcubature
pts <- matrix(nrow = 0, ncol = 2)
f1 <- function(X) {
pts <<- rbind(pts, X)
fn(X[1], X[2])
}
library(cubature)
round(hcubature(f1, c(-Inf, -Inf), c(Inf, Inf), tol = 1e-12)$integral, 6)
#> [1] 0
# Draw the points on the plot
plot(pts, type = "p")
# Now show contours of the function
x <- y <- seq(min(pts), max(pts), length.out = 100)
z <- outer(x, y, fn)
contour(x, y, z, col = "red", add = TRUE)
如果您将函数居中在 0 附近,那就没问题了。使用上面的代码运行
fn <- function(x, y) (pnorm(x)-pnorm(y))^2*(exp(-((x)^2-2*rho*(x)*(y)+(y)^2)/(2*(1-rho^2)))/(2*pi*sqrt(1-rho^2)))
并将结果打印为 0.134783。
推荐阅读
- angular - Angular8+ ngswitch 嵌套组件不更新视图
- asp.net-mvc - 为什么数据没有传输到控制器?
- c - 打印矩阵地址而不是值 | C
- angular - 错误类型错误:无法读取 ngx-leaflet 和 esri-leaflet-geocoder 上未定义的属性“topleft”
- ansible - Ansible中有多个json_query?
- node.js - 如何强制 Eclipse 使用特定版本的 NodeJS 来修复错误“无法确定 Node.js 版本”?
- php - Prestashop 自定义模块变量传递给 Theme .tpl 文件
- flutter - 未处理的异常:MissingPluginException(对于 Flutter 上的许多包,在通道 plugins.flutter.io/ 上找不到方法 getAll 的实现
- iphone - 如何在 Xcode 11.3.1 中测试 3.5 屏幕尺寸的布局,特别是 iPhone 4s?
- javascript - 设置最后做某事的倒计时