目标是绘制随着点数变化的显示不同情况下的
模拟元首率pi 用蒙特卡罗法
% title也会动
% 多张图组成动图
for i = [500,1000,2000,5000,10000];%i依次等于500,1000,2000,5000,10000
x1 = linspace(0,1,1000);%生成一系列的点
y1 = (1-x1.^2).^0.5;
x2 = rand([1,i]);%生成点
y2 = rand([1,i]);
count =0;
for j= 1:i
if x2(j)^2 + y2(j)^2 <= 1
count = count+1;
end
end
plot(x1,y1,'.k',x2,y2,'.');
title([num2str(count)+" / "+num2str(i)+"*"+"4"+"="+num2str((count/i)*4)]);%num2str()转化成字符串
axis square;
%生成一个gif的格式代码
%运行后在当前文件夹生成一个test.gif文件,单击右键在matlab外部生成即可
frame = getframe(gcf); %捕获坐标区或图窗作为影片帧 %gcf是返回的figure,f是figure的首字母
I = frame2im(frame); %返回与影片帧关联的图像数据
[I,map]=rgb2ind(I,256); %将RGB 图像转换为索引图像I,关联颜色图为 map
if i==500
imwrite(I,map,'test.gif','gif','LoopCount',inf,'DelayTime',0.2); %0.2是延时时间,可以更改
else
imwrite(I,map,'test.gif','gif','WriteMode','append','DelayTime',0.2);
end
end