[Math] Evaluating double integrals using monte carlo methods in matlab.

MATLABmonte carlo

I used the monte carlo method to integrate $\int_{0}^{1}x^2dx$ in matlab.

My matlab code was simply the following:
A=1;
N=10000;
s=0;
for i=1:N
x=rand;
y=rand;
if y<= x^2;
s=s+1;
end;
end;
I=A*s/N

If I wanted to extend this matlab code to evaluate a double integral, how would I do that? For example, what if I was given $\int_0^1\int_0^1x^2y dxdy$?

Best Answer

This is nearly the same. Only now you are in three dimensions. $x^2y$ still has values in $[0,1]$, so you take random $x,y,z$ from $[0,1]$ each (So still $A=1$ only technically it's a volume now, not an area) and just check if $z \leq x^2y$, that is, that you are under the graph. The rest of your code can stay identical.