蒙特卡罗模拟是基于概率的一种算法。使用随机数或者伪随机数用计算机实现统计模拟或抽样。一个很简单的例子是求pi。
求pi常见的有两种方法,一种是在平行线间插针,一种是在一个正方形的内接圆上随机投点,原理都是类似的。下面给出在内接圆上投点的matlab代码及结果。
%%% Use Monte Carlo simulation to calculate the pi value
function s=getpi(n)
sum=0
for i=1:n
x=rand();
y=rand();
if (x 2+y 2)<1
sum =sum+1;
end
end
s=4*sum/n;
end
The results of 1000 and 10000 random experiments are as follows:
getpi (1000)
sum =
0
years =
3.1600
getpi (10000)
sum =
0
years =
3.1312
可以看到,随着实验次数的增加,模拟的结果更加逼近真实值了。
以上就是今日学习笔记,请多多指教,鞠躬!