Monte Carlo

蒙特卡洛算法就是基于随机模拟,不断的进行抽样,不断的逼近期待的结果;例如下面计算圆周率π:

实现过程如下:

n=1e4;  
x=rand(n,1);
y=rand(n,1);  
%下面为画直线框
%起始点集为(0,0),(1,0),(0,1)(1,1)
Ax=[0 1 0 1];   %起始点横坐标
Ay=[0 0 1 1];   %起始点纵坐标 
%终点集为(1,0),(1,1),(0,0),(0,1)
Bx=[1 1 0 0];   %终点横坐标
By=[0 1 0 1];   %终点纵坐标
X=[Ax ; Bx];
Y=[Ay ; By];
plot( X,Y,'r','LineWidth',1);
axis([-0.5 1.5 -0.5 1.5]);
hold on
count=0;
for i=1:n
    if x( i )^ 2 + y( i )^ 2 <1
		count = count+1;
        plot(x(i),y(i),'.b','LineWidth',0.05)   %圆内的点就画出
    end
end
disp(4*count/n)

运行结果如下

因为是随机模拟的,所以每次的运行结果都会不同
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44961737/article/details/105722685