Integrate over an integral in R

前端 未结 2 1657
一向
一向 2021-01-13 09:54

I want to solve the following in R:

0H [π(t) ∫tH A(x) dx ] dt <

2条回答
  •  無奈伤痛
    2021-01-13 10:47

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

提交回复
热议问题