How to use Monte Carlo method to find volume?

3.7k Views Asked by At

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!

2

There are 2 best solutions below

0
On

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

0
On

I think you mean area rather than volume, because you only have x and y dimensions.

You have already defined a rectangle that includes your irregular shape. The only need to add two simple steps:

  1. Find the proportion of points of that rectangle. For that you can use mean.
  2. Multiply the result of step 1 by the rectangle area, which is (1-0)*(13-10).

So:

area = mean(y>=12*cos(x) &  y>=10+x.^3)*(1-0)*(13-10);

is the desired result.

Note that your condition

y>=12cos(x), and y>=10+x^(3)

is translated into Matlab as

y>=12*cos(x) & y>=10+x.^3

where & is logical "and" and .^ is element-wise power. The result of this expression is a vector of 1 and 0 values, depending on whether the condition is met or not. So the mean of that vector is the proportion of points that fulfill the condition.