return0;
}
else
h=-0.25*h;}
}
}
doublefuntion2(doublex){
doublef2=x*x*x*x*x+2*x*x*x*x-4*x*x*x+x*x+x+2;
returnf2;
}
4.黄金分割
#include
usingnamespacestd;
doublegoldivide(doublec,doubleh,doubleo);
doublef(doublex);
doublea[30];
doubleb[30];
doubleu[30];
doublev[30];
doubleeps;
intmaxstep=30;
intmain(){
cout<<"Pleaseentertheinitial区间左端点a:
";
cin>>a[0];
cout<<"andentertheinitial区间左端点b:
";
cin>>b[0];
cout<<"thelastentertheeps:
";
cin>>eps;
goldivide(a[0],b[0],eps);
return0;
}
doublegoldivide(doublec,doubleh,doubleo){
u[0]=a[0]+(1-0.618)*(b[0]-a[0]);
v[0]=a[0]+0.618*(b[0]-a[0]);
for(intk=0;kcout<<"a["<if((b[k]-a[k])doublex0=0.5*(b[k]+a[k]);
cout<cout<<"f(x0)="<return0;
}
elseif(f(u[k])>f(v[k])){
a[k+1]=u[k];
b[k+1]=b[k];
u[k+1]=v[k];
v[k+1]=a[k+1]+0.618*(b[k+1]-a[k+1]);
f(v[k+1]);
}
else{
a[k+1]=a[k];
b[k+1]=v[k];
v[k+1]=u[k];
u[k+1]=a[k+1]+(1-0.618)*(b[k+1]-a[k+1]);
f(u[k+1]);}}}
doublef(doublex){
doublef1=x*x*x*x*x+2*x*x*x*x-4*x*x*x+x*x+x+2;
returnf1;
}
5.不确定精度一维搜索
#include
doublef(doublex1,doublex2);
doublef1(doublex1,doublex2);
doublef2(doublex1,doublex2);
intxk[2]={-1,1};
intsk[2]={1,1};
doublexk1[2];
doublec1=0.1;
doublec2=0.5;
doublea=0;
doubleb;
doubler=1;
intmain(){
usingnamespacestd;
doublefk=f(xk[0],xk[1]);
doublegk[2]={f1(xk[0],xk[1]),f2(xk[0],xk[1])};
doublegkTsk=gk[0]*sk[0]+gk[1]*sk[1];
cout<<"fk="<cout<<"gkTsk="<for(;;){
xk1[0]=xk[0]+r*sk[0];
xk1[1]=xk[1]+r*sk[1];
doublefk1=f(xk1[0],xk1[1]);
doublegk1[2]={f1(xk1[0],xk1[1]),f2(xk1[0],xk1[1])};
doublegk1Tsk=gk1[0]*sk[0]+gk1[1]*sk[1];
cout<<"r="<cout<<"f(k+1)="<cout<<"g(k+1)Tsk="<if(fk-fk1>=-c1*r*gkTsk){
if(gk1Tsk>=c2*gkTsk){
doublerk=r;
cout<<"rk=:
"<cout<<"x(k+1)=:
("<return0;
}
else
{a=r;r=min(2*r,0.5*(r+b));}
}
else
{b=r;r=0.5*(r+a);}
}
}
doublef(doublex1,doublex2){
doublezf=100*(x2-x1*x1)*(x2-x1*x1)+(1-x1)*(1-x1);
returnzf;
}
doublef1(doublex1,doublex2){
doublezf1=-400*(x2-x1*x1)*x1-2*(1-x1);
returnzf1;
}
doublef2(doublex1,doublex2){
doublezf2=200*(x2-x1*x1);
returnzf2;
}
6.进退法
#include
usingnamespacestd;
doubledilemma(doublez,doublec);
doublef(doublex);
doublet[30];
doubleh;
doublea;
doubleb;
intmaxstep=30;
intmain(){
cout<<"Pleaseenterthevaguevaluet0:
";
cin>>t[0];
cout<";
cin>>h;
dilemma(t[0],h);
return0;
}
doubledilemma(doublez,doublec){
cout<<"f(t[0])="<t[2]=t[0]+h;
cout<<"f(t[2])="<if(f(t[2])>f(t[0]))
h=-h;
for(;;){
t[1]=t[0]+h;
f(t[1]);
cout<<"f(t[1])="<if(f(t[1])<=f(t[0])){
h=2*h;
t[2]=t[0];
t[0]=t[1];
}
else{
cout<<"f(t[1])>f(t[0])theend"<a=min(t[1],t[2]);
b=max(t[1],t[2]);
break;
}
}
cout<<"it'stheansweryouwant:
êo["<cout<<"andt[0]="<<0.5*(a+b);
return0;
}
doublef(doublex){
doublef1=x*x*x*x*x+2*x*x*x*x-4*x*x*x+x*x+x+2;
returnf1;
}