我想在 R 中解决以下问题:
∫0H [π(t) ∫tH A(x) dx] dt
其中 π(t) 是先验,A(x) 是下面定义的 A 函数。
prior <- function(t) dbeta(t, 1, 24)
A <- function(x) dbeta(x, 1, 4)
expected_loss <- function(H){
integrand <- function(t) prior(t) * integrate(A, lower = t, upper = H)$value
loss <- integrate(integrand, lower = 0, upper = H)$value
return(loss)
}
由于 π(t), A(x) > 0,expected_loss(.5) 应小于 Expected_loss(1)。但这不是我得到的:
> expected_loss(.5)
[1] 0.2380371
> expected_loss(1)
[1] 0.0625
我不确定我做错了什么。
最佳答案
在您的integrand
中,lower = t
未矢量化,因此对integration的调用没有达到您的预期*。 t
上的矢量化解决了这个问题,
expected_loss <- function(H){
integrand <- function(t) prior(t) * integrate(A, lower = t, upper = H)$value
vint <- Vectorize(integrand, "t")
loss <- integrate(vint, lower = 0, upper = H)$value
return(loss)
}
expected_loss(.5)
# [1] 0.7946429
expected_loss(1)
# [1] 0.8571429
*:仔细观察integrate
发现,默认允许将向量传递给下层和/或上层,但只考虑第一个值。当在更宽的间隔上积分时,求积方案选择了距离原点更远的第一个点,导致您观察到的不直观的下降。
向 r-devel 报告此行为后,this user-error will now be caught by integrate感谢 Martin Maechler(R-devel)。
关于r - 对 R 中的积分进行积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36275909/