使用进退法选取极小值所在区间,然后用黄金分割法找到极小值
%%%%%%%%%%%%%%%%%%%%%%%%%%-----进退
-------%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear;
syms x; %创建一个符号变量
h=diff(f(x),x); %求对x的一阶导数
x0=10;
g=subs(h,x0); %在x0处h的值
%%%%%%%%---------初始值在极小
-------%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if g<0
step=10;x1=x0+step;
if f(x1)<=f(x0)
step=2*step;
x2=x1+step;
while f(x1)>f(x2)
x0=x1;x1=x2;
step=2*step;
x2=x1+step;
end
else
step=0.5*step;
x2=x1-step;
while f(x0)>f(x2)
x0=x0+0.5*step;
x2=x2+step;
end
end
a=x0;
b=x2; 值点左侧的时候法求合适区间
disp(['f(x)极小值点所在区间为(',num2str(a),',',num2str(b),')']); end
%%%%%%%%%%%%%%%%%%%%当极小值点在初始点右侧时%%%%%%%%%%%
if g>0
step=6;x1=x0-step;%以下方法仅仅适用于初始值在极小值点右侧的时候
if f(x1)<=f(x0)
step=2*step;
x2=x1-step;
while f(x1)>f(x2)
x0=x1;x1=x2;
step=2*step;
x2=x1-step;
end