Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

double integral in R

I'm wondering how to code that takes double integrals in R. I already referred two similar questions.

calculating double integrals in R quickly

double integration in R with additional argument

But I'm still confused how I can get my question from those answers. My question is following.

I would like to code this calculations in R.

enter image description here

From my hand and Wolfram alpha calculation, it becomes 16826.4. I know how to take a integral if both integrals are from exact numbers using adaptIntegrate(). But I'm not sure how to do in my case. Could you guys help me? Thank you so much in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let me start with the code and then step through to explain it.

InnerFunc = function(x) { x + 0.805 }
InnerIntegral = function(y) { sapply(y, 
    function(z) { integrate(InnerFunc, 15, z)$value }) }
integrate(InnerIntegral , 15, 50)
16826.4 with absolute error < 1.9e-10

The first line is very easy. We just need the function f(x) = x + 0.805 to be able to compute the inner integral.

The second step is the only thing that is tricky. It seems natural to compute the inner integral with a simpler expression function(z) { integrate(InnerFunc, 15, z)$value } and just integrate it. The problem with that is that integrate expects a vectorized function. You should be able to give it a list of values and it will return a list of values. This simple form of the first integral just works for one value at a time. That is why we need the sapply so that we can pass in a list of values and get back a list of values (the first definite integral).

Once we have this vectorized function for the inner integral, we can just pass that to integrate to get the answer.

Later Simplification
While the above sapply method worked, it is more natural to use the function Vectorize like this.

InnerFunc = function(x) { x + 0.805 }
InnerIntegral = Vectorize(function(y) { integrate(InnerFunc, 15, y)$value})
integrate(InnerIntegral , 15, 50)
16826.4 with absolute error < 1.9e-10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...