Monte Carlo Pi while loop iterations

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

Antworten (2)

Roger Stafford
Roger Stafford am 18 Sep. 2014
Bearbeitet: Roger Stafford am 18 Sep. 2014

2 Stimmen

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 Kommentare

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 am 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.

Melden Sie sich an, um zu kommentieren.

Image Analyst
Image Analyst am 18 Sep. 2014

0 Stimmen

I'm not really sure that you're using the right formula. See this discussion for someone else's code.

1 Kommentar

Roger Stafford
Roger Stafford am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Graphics Performance finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 18 Sep. 2014

Kommentiert:

am 19 Sep. 2014

Community Treasure Hunt

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

Start Hunting!

Translated by