之前回答过题主的另一个相关问题(编号1384750375215298220),其中的随机数生成稍微有点问题,请把其中的
改为
以使得随机数在圆内均匀分布。
这个问题的改动主要是考虑了守门员这个因素,另外图形显示的实现上也有些变化。参考代码如下:
d = inputdlg('射门次数R','试验设置',1,{'100'});
if isempty(d), return, end
R = round(str2double(d{1}));
% R = 100;
L = 4;
W = 2;
D = sqrt(L^2+W^2);
% 绘图
clf
t = linspace(0,2*pi,200);
plot(D/2*cos(t),D/2*sin(t),'linewidth',2);
hold on
[x,y] = meshgrid((-2:2)*L/4, (-1:1)*W/2);
surf(x,y,x*0,'Facealpha',0.3,'Edgealpha',0.5)
h = plot(NaN,NaN,'ro');
k1 = patch(NaN,NaN,'k','Facealpha',0.6);
k2 = patch(NaN,NaN,'k','Facealpha',0.6);
axis equal
% 守门员区域定义
K{1} = [-L/4 L/4 -W/2 W/2];
K{2} = [-L/2 -L/4 0 W/2; -L/4 0 -W/2 0];
K{3} = [0 L/4 -W/2 0; L/4 L/2 0 W/2];
K{4} = [-L/2 0 -W/2 0];
K{5} = [0 L/2 -W/2 0];
% 模拟
P = zeros(R,1);
Q = P;
for n = 1 : R
r = sqrt(rand)*D/2; % 半径的概率与其长度一致
t = rand*2*pi;
x = r.*cos(t);
y = r.*sin(t);
% 判断在球门范围内
P(n) = abs(x)
% 判断是否被守门员扑出
k = ceil(rand*5);
if any( x>K{k}(:,1) & x
end
% 更新绘图
set(k1,'xData',K{k}(1,[1 2 2 1]),'yData',K{k}(1,[3 3 4 4]))
if size(K{k},1) > 1
set(k2,'xData',K{k}(2,[1 2 2 1]),'yData',K{k}(2,[3 3 4 4]))
else
set(k2,'xData',NaN,'yData',NaN)
end
set(h,'xdata',x,'ydata',y);
if ~P(n)
set(h, 'color','m');
elseif P(n) && ~Q(n)
set(h, 'color','g');
else
set(h, 'color','r');
end
drawnow
end
% 计算概率
p = mean(P)
q = mean(Q)
mean(P.*~Q)