# Approximating integrals using Monte Carlo simulation in R

How do I approximate the following integral using MC simulation?

$$\int_{-1}^{1} \int_{-1}^{1} |x-y| \,\mathrm{d}x \,\mathrm{d}y$$

Thanks!

Edit (Some context): I am trying to learn how to use simulation to approximate integrals, and am getting some practice done when I ran into some difficulties.

Edit 2+3: Somehow I got confused and thought I needed to split the integral into separate parts. So, I actually figured it out:

n <- 15000
x <- runif(n, min=-1, max=1)
y <- runif(n, min=-1, max=1)
mean(4*abs(x-y))

-
You are on the right track! The answer you give is very close to being correct. You're missing one tiny part. (Hint: What is the pdf of a $\mathcal U(-1,1)$ random variable)? –  cardinal Oct 23 '11 at 22:51
It's 0.5. So I need to multiply by two 2's to give: 'mean(4*abs(x-y))'. Did I finally get it? –  My Name Oct 23 '11 at 23:01
(+1) Yes! :) You may have to wait a few (8?) hours, but you should consider coming back and placing your edit into an answer so that other users (like me) can upvote it. Welcome to the site! I hope to see you continue to participate here. Cheers. :) –  cardinal Oct 23 '11 at 23:07
One point to add: I find maxima extremely useful for symbolic math. If I had to do analytical calculations myself, I'd have the same problem as @EpiGrad. But in maxima, you could do integrate(integrate(abs(x-y), y, -1, 1), x, -1, 1); and get the answer 8/3. –  Karl Oct 24 '11 at 0:02
For the R interested, though not as elegant at the maxima code posted by Karl, one can do integrate(Vectorize(function(y) integrate(function(x) abs(x-y), -1, 1)\$value), -1, 1) and get a numeric approximation. Using the cubature package adaptIntegrate(function(x) abs(x[1] - x[2]), c(-1, -1), c(1, 1)) can be used. This is just to give a couple of ideas for numeric evaluation of integrals that could come in handy, for instance when testing if a simulation works correctly. –  NRH Oct 24 '11 at 13:14

## 2 Answers

Just for reference, a low dimensional integral like that is usually more efficiently done via deterministic quadrature instead of Monte Carlo. Monte Carlo comes into its own at about 4 to 6 dimensions. Got to learn it in low dimensions first, of course...

-
I guess that's why this question is tagged homework :-). –  whuber Jan 13 '12 at 21:18

You can do it in Excel with Tukhi.

Enter

=tukhi.average(abs(2*rand()-1 - (2*rand()-1)))


and hit the run button.

-