Monte Carlo Pi while loop iterations
3 views (last 30 days)
Show older comments
This is the part of the problem i am having some trouble with
How many iterations are needed to reach a pi value that is within an error of 0.001 from the exact value of pi? Do so constructing a while loop.
This is the coding that i wrote for part 1. Now for part 2, I'm a bit stumped. Someone give me a starting point, Please!
L is mandated at 10
N is mandated at under 5000
if true
clear, clc
figure;
axis equal off;
hold on;
L = 10;
R = L/2;
axis ([-R R -R R]);
N= 2000;
Nin = 0;
for k=1:N
x = L*rand-R;
y = L*rand-R;
if (x^2+y^2)<= R^2
Nin= Nin + 1;
plot(x,y,'.r');
else
plot(x,y,'.b');
end
end
MCpi = 4*Nin/N;
fprintf ('Using %d iterations, pi was calculated to be: %f.',N,MCpi)
end
0 Comments
Answers (2)
Roger Stafford
on 18 Sep 2014
Edited: Roger Stafford
on 18 Sep 2014
Roughly speaking, the expected variance from the mean in an independent random series is proportional to the reciprocal of the square root of the number of trials. Consequently I would suggest using something like a million or more trials to achieve that small a level of error. The reciprocal of the square root of a million is 0.001. You have only done 2000.
2 Comments
Roger Stafford
on 19 Sep 2014
Waiting until your series at some point happens to have a fraction of hits differing from a known pi/4 seems a little ridiculous to me. You have to know pi in advance for it to work, so why bother? The only valid approximation of pi would come from selecting a series sufficiently long to ensure that the value you obtain is almost certainly that close to pi, and that length as I have said is surely somewhere in the millions.
Image Analyst
on 18 Sep 2014
I'm not really sure that you're using the right formula. See this discussion for someone else's code.
1 Comment
Roger Stafford
on 18 Sep 2014
His formula is correct. His 10 x 10 square box has an area of 100 and the circle centered in the box has an area of pi*5^2, so the probability of hitting inside the circle is p = 25*pi/100 = pi/4. So 4*p where p = Nin/N ought to approximate pi.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!