[Math] How to use Monte Carlo method to find volume

MATLABmonte carlovolume

So the question asks to use the Monte Carlo method to find the volume of an irregular figure defined as:

0<=x<=1, 10<=y<=13, y>=12cos(x), and y>=10+x^(3)

I have managed to get up to this part, where I initialize a random generator between two points for x and y.

n = 100000;
x = (1-0)*rand(n,1); y = (13-10)*rand(n,1)+10;

I have no idea how to do the rest this on MATLAB.
I don't need to have a function for these methods, just line-by-line code is alright.

Any help would be appreciated. Thank you!

Best Answer

I'll show you a different example, from which you should hopefully be able to work out your problem.

I'm going to approximate the area of a circle of radius 1. Firstly, my $x$ and $y$ coordinates will range from -1 to 1.

n=10000;
x=(1-(-1))*rand(n,1)+(-1);
y=(1-(-1))*rand(n,1)+(-1);

Now one of these points $(x,y)$ is inside the circle if the distance from the origin to that point is less than or equal to 1. The distance from the origin to the point is $r=\sqrt{x^2+y^2}$, so calculate that for every point:

r=sqrt(x.^2+y.^2); %// note I used element-wise dot exponentiation

Now see which points lie in the circle:

countInsideCircle=sum(r<=1) %// the number of points less than one unit from the origin

To calculate the area of the circle, first find the proportion of points that lie in the circle:

proportionInsideCircle=countInsideCircle/n

and then multiply by the area of the surrounding square (sides of length 2, so area is 4):

areaOfCircle=4*proportionInsideCircle

I did it and got A=3.1588 which isn't too bad as an approximation to $\pi$.

For your shape, you wont need the radius calculation, and you will just have to modify the countInsideCricle line to include the points you want, and also be careful about the area of your bounding box, it wont be 4.

Hint: s=sum(0<=x && x<=1 && y>=12*cos(x)) should give you the number of points satisfying $0\leq x\leq 1$ and $y\geq 12\cos x$.