Cross Validated is a question and answer site for people interested in statistics, machine learning, data analysis, data mining, and data visualization. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I approximate the following integral using MC simulation?

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


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)
share|improve this question
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

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...

share|improve this answer
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.


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

and hit the run button.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.