Monte Carlo(蒙特卡罗)
来源:互联网 发布:数据分析助理干啥的 编辑:程序博客网 时间:2024/05/22 12:47
Monte Carlo(蒙特卡罗)
Monte Carlo 是一种基于计算机的求解方法,利用计算机在input domain上产生一组随机数,通过这一组随机数计算出一组结果。通过这样的一个反复过程最终大致得到待求解值。
具体过程:
- Define a domain of possible inputs
- Generate inputs randomly from a probability distribution over the domain
- Perform a deterministic computation on the inputs
- Aggregate the results
代码:
注意:1. 通过text动态的显示文本,要将上一次的text删除,通过它的句柄删除它;
2. 画图的动态显示,需要pause函数暂停才能显示;
i=0;h=figure(1);count1 = 0;count2 = 0;while i<100000location = rand(1,2);if sum((location).^2)<1 count1 = count1 + 1; plot(location(1),location(2),'Color','r','Marker','.','LineWidth', 4); axis([0 1 0 1]) hold all;else count2 = count2 + 1; plot(location(1), location(2), 'Color', 'b','Marker', '.','LineWidth', 4);endi =i+1;pi = double(4*count1/i);pause(0.0000001);if i ==1 ha = text(0.5,1.06,['n = ', num2str(i)]); hb = text(0.8,1.06,['\pi = ', num2str(pi)]);else delete(ha); delete(hb); ha = text(0.5,1.06,['n = ', num2str(i)]); hb = text(0.8,1.06,['\pi = ', num2str(pi)]);endend
阅读全文