skyindeer skyindeer - 1 month ago 19
R Question

2-fold (repeated) integral in R

I want to compute a 2-fold repeated integral (not double integral) in R, for example,



where



In practice, both f(x) and g(x) are quite complicated, but to run an experiment, let's simplify g(x)=1 and f(x)=cos(x), in R I use

integrate
to compute:

> phi = function(x){integrate(function(x){cos(x)},lower=x,upper=3)[["value"]]^2}

> foldintegral = integrate(phi,lower=0,upper=3)


And I got this error message:

Error in integrate(phi, lower = 0, upper = 3) :
evaluation of function gave a result of wrong length


Any Idea how to do that ?

Answer

All that is needed is

integrate(Vectorize(phi), lower=0, upper=3)
# 1.067943 with absolute error < 1.2e-14

Compare

phi(1)
#[1] 0.4904915

phi(1:3)
# [1] 0.4904915

Vectorize(phi)(1:3)
# [1] 0.4904915 0.5900965 0.0000000

integrate expects a vectorized function.

Comments