Integrate over an integral in R

杀马特。学长 韩版系。学妹 提交于 2019-12-01 05:52:02

In your integrand, lower = t is not vectorised, so the call to integrate is not doing what you expected*. Vectorising over t fixes this issue,

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

*: a closer look at integrate revealed that passing vectors to lower and/or upper was silently allowed, but only the first value was taken into account. When integrating over a wider interval the quadrature scheme picked a first point further from the origin, resulting in the unintuitive decrease that you observed.

After reporting this behaviour to r-devel, this user-error will now be caught by integrate thanks to Martin Maechler (R-devel).

In this particular case, you don't need to Vectorize since the integral of dbeta is already implemented in R through pbeta. Try this:

prior <- function(t) dbeta(t, 1, 24)
#define the integral of the A function instead
Aint     <- function(x,H) pbeta(H, 1, 4) - pbeta(x,1,4)
expected_loss <- function(H){
  integrand<-function(x) Aint(x,H)*prior(x)
  loss          <- integrate(integrand, lower = 0, upper = H)$value
  return(loss)
}
expected_loss(.5)
#[1] 0.7946429
expected_loss(1)
#[1] 0.8571429
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!