skyindeer skyindeer - 1 year ago 125
R Question

2-fold (repeated) integral in R

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


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

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 Source

All that is needed is

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


#[1] 0.4904915

# [1] 0.4904915

# [1] 0.4904915 0.5900965 0.0000000

integrate expects a vectorized function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download