一维搜索进退法
function f=getvalue(t)
f=t^3-2*t+1;
function [a,b]=myfun(t,h,alpha)
t0=t;
k=0;
fi0=getvalue(t0);
for count=1:1:100
t1=t0+h;
fi1=getvalue(t1);
if(fi1<fi0)
h=alpha*h;
t=t0;
t0=t1;
fi0=fi1;
k=k+1;
else
if(k~=0)
if(t>t1)
a=t1;
b=t;
else
a=t;
b=t1;
end
break;
else
h=-h;
t=t1;
end
end
end
结果:
>> [a,b]=myfun(0,1,2)
a=0,b=3
黄金分割法
function [value,a,b]=myfun(m,n,alpha)
tao=0.618;
ephsilo=alpha;
a=m;
k=0;
b=n;
lamenda=a+(1-tao)*(b-a);
miu=a+tao*(b-a);