# [MATLAB/编程]报童的诀窍/报童问题-图解法和二分法

## MATLAB编程题目 : 报童的诀窍

### 1．的图解法（编程）

``````clc;
clear;

syms y1 y2 a b c z
a = 1;
b = 0.75;
c = 0.6;
z = 450:0.01:550;

y1 = (a-b)/(a-c);
y2 = normcdf(z,500,50)-normcdf(0,500,50); %分布函数

plot([450,550],[y1,y1])
hold on;
plot(z,y2);

grid on;

% 输出交点
fsolve(@(z) (a-b)/(a-c) - normcdf(z,500,50)-normcdf(0,500,50),[450 550])
``````

@运算符创建句柄，@(x)为函数的入口，指定函数当中的变量x为函数的输入，在接受函数和进行求解时，对象为x。

``````sqr = @(z) 2.*z
sqr(3)

% 输入的变量默认输入到z当中
-> 6
``````

`fsolve(@(x) f(x))`解决的问题为`f(x)=0`

``````fsolve(@(z) (a-b)/(a-c) - normcdf(z,500,50)-normcdf(0,500,50),[450 550])
``````

### 2．的数值解法（二分法/编程）

erfen.m

``````function y=erfen(a,b)  %二分法
if fun(a)*fun(b)<0
c=(a+b)/2;
while abs(fun(c))>1.0e-4    % 二分分界点
if fun(a)*fun(c)<0
b=c; c=(a+b)/2;
elseif fun(c)*fun(b)<0
a=c; c=(a+b)/2;
end
end
y=c;
elseif fun(a)==0
y=a;
elseif fun(b)==0
y=b;
else
disp('区间中不存在根');
end
return;
``````

main.m

``````function main()
clc;
n = erfen(450,550)

a=1;b=0.75;c=0.6;
r=n+1;
while (a-b)*n*normpdf(r,500,50)>exp(-6)
r=r+1;
end
r=n+1:r;
G = sum((a-b)*n*normpdf(r,500,50)); % 离散值求和
r=0:n;
G = G+sum(((a-b)*r-(b-c)*(n-r)).*normpdf(r,500,50))	% 离散值求和
return;
``````

fun.m

``````function y=fun(z)  %方程
a = 1;
b = 0.75;
c = 0.6;
y = (a-b)/(a-c) - normcdf(z,500,50) - normcdf(0,500,50); % 构造函数差，方便二分查找
return;
``````

1.计算正态变量的概率密度函数的调用形式为：`Y=normpdf(X,mu,sigma)`

mu为μ，sigma为σ。

2.计算正态变量的分布函数的调用形式为：`P=normcdf(X,mu,sigma)`