I am calculating the value of the integral
$$
int_0^1int_1^2(r-u)r drdu
$$
I would like to understand how the following error is handled in R.
Looking around the forum, I realized that a vectorization of the first of the two integrals (in r) is required to compute the second one (in u). Therefore I assume that the following code is the correct way of solving the calculation (tell me please If I am wrong).
fI <-
function(u){
integrand <- function(r, u){
(r - u) * r
}
sapply(X = u,
function(z){
integrate(f = integrand, lower = 1, upper = 2, u = z)$value
})
}
integrate(f = fI, lower = 0, upper = 1)
which returns
1.583333 with absolute error < 1.8e-14.
However, I could notice that even when incorrectly defining fI
without vectorization, a small trick allows the integral to be calculated (I assume wrongly)
fI <-
function(u){
integrand <- function(r, u){
((r - u) * r)
}
integrate(f = integrand, lower = 1, upper = 2, u = u)$value
}
integrand2 <-
function(u){
rep(1, length(u)) * fI(u = u)
}
integrate(f = integrand2, lower = 0, upper = 1)
which delivers a different result
1.5 with absolute error < 1.7e-14.
Can anybody explain me what is going on in the second case and what is the value passed as u
in fI(u=u)
inside the integrand
function? I understand that in this way u
cannot take a range of values.
I need to understand this mechanism because my actual calculation is a bit more involved and I would need to understand what is going on in this simplified case.