-
蒙特卡罗法
蒙特卡罗法也称统计模拟法、统计试验法,特别适用于一些解析法难以求解甚至不可能求解的问题。前提必须建立在一个随机试验之上,利用事件发生的频率作为事件发生的概率的近似值,试验次数越多,求得未知数的值将越准确。
-
模拟圆周率思路
利用 1/4 单位圆的面积:
S = 1/4 * π R^2
S = 1/4 π
在 1×1 的正方形内随机点在 1/4 圆内概率:
理论值 :P = 1/4 π
试验值 :总点数(allpoints) / 在1/4 单位圆内的点数(count)
求得圆周率:
π count / allpoints * 4
-
matlab代码
allpoints = input('请输入生成的总点数');
count = 0;
for i =1 : allpoints
if rand^2 + rand^2 <= 1 %rand是0~1的随机数
count = count + 1;
end
end
res = count / allpoints*4;
disp(res);
-
GIF动图代码
for i = [500, 1000, 2000, 5000, 10000] x1 = linspace(0,1,10000); 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 end plot(x1,y1,'k.',x2,y2,'.'); title([num2str(count)+"/"+num2str(i) +"4"+"="+num2str(count/i*4)]); axis square; frame = getframe(gcf); I = frame2im(frame); [I,map]=rgb2ind(I,256); if i==500 imwrite(I,map,'test.gif','gif','LoopCount',inf,'DelayTime',0.5); else imwrite(I,map,'test.gif','gif','WriteMode','append','DelayTime',0.5); end
截取图像: