Monte Carlo Pi while loop iterations
Mostrar comentarios más antiguos
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
Respuestas (2)
Roger Stafford
el 18 de Sept. de 2014
Editada: Roger Stafford
el 18 de Sept. de 2014
2 votos
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 comentarios
Timothy
el 18 de Sept. de 2014
Roger Stafford
el 19 de Sept. de 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
el 18 de Sept. de 2014
0 votos
I'm not really sure that you're using the right formula. See this discussion for someone else's code.
1 comentario
Roger Stafford
el 18 de Sept. de 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.
Categorías
Más información sobre Graphics Performance en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!