2007年4月12日木曜日

モンテカルロ法によるPIの推定


%モンテカルロ法によるPIの推定
No = 100;
for i=1:No
N = 100*i;
x = rand(N,1); %一様分布の擬似乱数
y = rand(N,1); %一様分布の擬似乱数
r = x.^2+y.^2;
NS(i) = N;
PI(i) = 4*sum(r<1)/N;
end
r = 1;
c = 2;
subplot(r,c,1);
hold on;
plot(NS,PI,'.k');
plot(NS,ones(No,1)*pi,'--r');
xlabel('繰り返し回数');
ylabel('\piの推定');
grid on;
hold off;
subplot(r,c,2);
hold on;
t = 0:0.01:pi/2;
rx = cos(t);
ry = sin(t);
plot(rand(No*100,1),rand(No*100,1),'.k');
plot(rx,ry,'r');
grid on;
hold off;
print('-dpng','-r80','pi_mento.png');

0 件のコメント: