MATLAB: I am new to Maltlab, i wanted to use a while loop to calculate pi using Montecarlo method. the code below is not giving me any answer can anyone help please.

matlab functionwhile loop

function [estimatepi,c] = estimatepi9(tol)
x=rand;
y=rand;
c=0;
hits=rand;
n= 0;
hit=[];
error=[];
estimatepi=[];
tol=0.0001;
error = abs(pi-estimatepi)-tol;
while error>tol
n=n+1;
x=rand;
y=rand;
hit=(x-0.5).^2+(y.^2)<=1;
for c=1:n;
hits=sum(hit);
estimatepi=4*hits/n;
end
end
end

Best Answer

Lilay - part of the problem is that estimatepi is set to an empty array. This variable is next used in the calculation of error which ends up being [] and so the comparison with tol fails...and the code in the while loop never gets executed. Just set estimatepi to zero and that should allow you to pass the while loop condition.
Next you need to consider the random numbers, x and y. I think the point of using this Monte Carlo approach is that with the more random numbers generated and the more that fall in the circle (of radius 1) then the better the estimate for pi. That means we need to generate n random variables:
n=n+1;
x=rand(n,1);
y=rand(n,1);
We need to count those random numbers (points) that fall in our circle of radius 1. I see that you almost have the calculation correct but I don't understand why you are subtracting 0.5 from the x values. I think that you can simplify this line to just
numHits=sum((x.^2 + y.^2)<=1);
sum is used to count the number "hits" within the circle. The for loop doesn't add anything (as it never uses c) and so it can be ignored. The estimate on pi is fine but you also need to re-calculate the error
estimatepi=4*numHits/n;
error = abs(pi-estimatepi);
I don't think that you need the - tol. Try adding the above changes and see what happens.
Something else to note: tol is an input parameter but then you set it to 0.0001. Either remove the assignment or the input parameter. As for the other local variables set outside of the while loop
x=rand;
y=rand;
c=0;
hits=rand;
n= 0;
hit=[];
ask yourself if they are necessary. Also what is the c that this function returns?