function piva=PiMonterCarlo(n)
x=0;y=0;d=0;
m=length(n);
pivalue=zeros(m,1);
for i=1:m
x=2*rand(n(i),1)-1;
y=2*rand(n(i),1)-1;
d=x.^2+y.^2;
pivalue(i)=4*sum(d<=1)/n(i);
end
if nargout==0
if m>1
figure;
plot(n,pivalue,'k.');
h=refline(0,pi);
set(h,'linewidth',2,'color','r');
text(1.05*n(end),pi,'\pi','FontSize',15);
xlabel('投点个数');
ylabel('\pi的模拟值');
else
figure;
plot(x,y,'r.');
hold on;
h=rectangle('Position',[-1 -1 2 2],'LineWidth',2);
t=linspace(0,2*pi,100);
plot(cos(t),sin(t),'k','LineWidth',2);
xlabel('X');ylabel('Y');
% title('Pi的模拟值:'num2str(pivalue));
axis([-1.1 1.1 -1.1 1.1]);axis equal;
end
else
piva=pivalue;
end
pi.png
网友评论