Integrate over the integral in R

I want to solve the following in R:

& int; 0 H [? ( t ) & int; t H A ( x ) dx] dt

Where & pi; (t) is the preceding, and A (x) is the function A defined below.

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

Since & pi; (t), A (x)> 0, expected_loss (.5) must be less than expected_loss (1). But this is not what I get:

 > expected_loss(.5) [1] 0.2380371 > expected_loss(1) [1] 0.0625 

I'm not sure what I'm doing wrong.

+5
source share
2 answers

In your integrand , lower = t not vectorized, so the call for integration does not do what you expected *. Vectorizing over t fixes this problem,

 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 showed that passing vectors of the lower and / or upper levels are tacitly allowed, but only the first value is taken into account. When integrating over a wider interval, the quadrature scheme removed the first point farther from the origin, resulting in an unintuitive decrease.

After reporting this r-devel behavior, this user error will now be caught by integration thanks to Martin Maecler (R-devel).

+8
source

In this particular case, you do not need Vectorize , since the integral from dbeta already implemented in R via pbeta . Try the following:

 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 
+6
source

Source: https://habr.com/ru/post/1245956/


All Articles