红针表示针与平行线相交,蓝针表示针没有与平行线想交
a行间距 b针长
% Buffon's Needle is one of the oldest problems in the field of geometrical probability.
clear,clc,close all
%绘制坐标系
n = 5;%线数目
a = 2;%线间距
x = ones(n+1,1)*[-a 10+a];
y = (0:n)'*[a a];
hold on
for i = 1:n+1
plot(x(i,:),y(i,:),'k','linewidth',1.5) %
axis equal
axis off
axis([-a,10+a,-1 n*a+1])
end
m = 100;%绘制针的数目
b = 1.5;%针长
m1 = 0;%初始相交次数
for k = 1:m
x = 10*rand; y = 10*rand;%针的起点;
phi = 2*pi*rand;
x1 = x + b*cos(phi); y1 = y + b*sin(phi); %针的终点;
t = 0;
for j=0:n
if (y-a*j)*(y1-a*j)<=0
t = 1;
break;
end
end
m1 = m1+t;
if t
plot([x x1],[y y1],'r','linewidth',1.5)
axis equal
axis off
axis([-a,10+a,-1 n*a+1])
else
plot([x x1],[y y1],'linewidth',1.5)
axis equal
axis off
axis([-a,10+a,-1 n*a+1])
end
pause(0.2)
end
axis equal
axis off
sprintf('pi的值近似为 %0.5g',2*b*m/(m1*a))
https://blog.sciencenet.cn/blog-292361-670293.html
上一篇:
上课抽样点名时想到的一道概率题下一篇:
用QQ帮学生解决一个MATLAB问题