Monte Carlo Pi while loop iterations

3 views (last 30 days)
Timothy
Timothy on 18 Sep 2014
Commented: Roger Stafford on 19 Sep 2014
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

Answers (2)

Roger Stafford
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
Timothy
Timothy on 18 Sep 2014
My apologies, I didnt specify that its from a sample size of less then 5000. I was thinking about something little less complex along the lines of:
while ( error > 0.001) && (N< 5000)
% Throw a dart
% compute the approximation value of Mcpi
% update the error = abs (pi – Mcpi)
% n = n + 1;
end
Roger Stafford
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.

Sign in to comment.


Image Analyst
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
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.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!