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$.
I assume you've got the gist of the idea behind the method from the comments above.
Here's the breakdown of the code:
- Pick a random vector (here a point in 3D) uniformly distributed over a box that contains the volume you'd like to sample. It doesn't have to be a snug fit, the box must simply be bigger.
- If the vector happens to be inside your the region, you'd like to find the volume of, let a counter variable tick one up, e.g. by
k = k+1
.
- Do this a large number of times, say $N$. Now $$\frac{k}{N}\approx\frac{\text{volume of region}}{\text{volume of box}},$$
and since the volume of the box is easy to calculate, you can find the desired volume. If $N\rightarrow \infty,$ the approximation will become an equality.
If you're having trouble implementing this in some specific software (like Python or Matlab), please ask over at Stack Overflow.
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
and then sum its entries. (Note that I used &, which is purposed for logical arrays, not &&, which is purposed for single booleans.)