[Math] Matlab Monte Carlo Method Volume Calculation

MATLABvolume

The question: use the Monte Carlo method to find the volume of intersection of, three cylinders, all of radius 3 units and infinite in length,with the axis of the first cylinder being the x-axis, the axis of the second cylinder being the $y$-axis and the axis of the third cylinder being the line with points $(1; 1; z)$ where $z \in \mathbb{R}$ is any real number.

I have tried this:

I have added the inequalities:
$$ x^2+z^2 \leq 3^2$$
$$ y^2+z^2 \leq 9 $$
$$ (x-1)^2+(y-1)^2 \leq 9$$
and obtained
$$(x-0.5)^2+(y-0.5)^2+z^2 \leq 13 $$

I have used the following code:

r=sqrt(13);
n=100000;
x=-r+(r-(-r))*rand(1,n);
y=-r+(r-(-r))*rand(1,n);
z=-r+(r-(-r))*rand(1,n);
dotsCube=0; dotsSphere=0;

for i=1:n
    dotsCube=dotsCube+1;            
    if (x(i)^2+z(i)^2 <= 9) & (y(i)^2+z.^2 <= 9) & ((x(i)-1)^2+(y(i)-1)^2 <= 9)
        dotsSphere=dotsSphere+1;    
    end;
end;


cubeV=(2*r)^3   
sphereV=cubeV*dotsSphere/dotsCube

But I get $0$ for sphereV

I do not understand why I cannot get the Volume.
Any help, hints would be appreciated.Thank you so much 🙂

Best Answer

The other answer pointed out that you have algebraic problems. You also have two code problems. One is that you have not assigned r, which will need to be large enough to contain the entire intersection. It looks like r=5 is sufficient, although not optimal.

The other problem is that your loop with i does not use x(i), y(i), etc. You need to do that (with scalar operations, not vector operations) if you're going to do this with a for loop. But there is a better way. You can make the logical vector

(x.^2+z.^2 <= 9) & (y.^2+z.^2 <= 9) & ((x-1).^2+(y-1).^2 <= 9) 

and then sum its entries. (Note that I used &, which is purposed for logical arrays, not &&, which is purposed for single booleans.)

Related Question