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
回答(2 个)
Roger Stafford
2014-9-18
编辑:Roger Stafford
2014-9-18
2 个投票
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 个评论
Timothy
2014-9-18
Roger Stafford
2014-9-19
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
2014-9-18
0 个投票
I'm not really sure that you're using the right formula. See this discussion for someone else's code.
1 个评论
Roger Stafford
2014-9-18
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!