📄 fletchbv3.cpp
字号:
#include<iostream.h>
#include<math.h>
#define N 10
//cF41 FLETCBV3
//*
//* Initial Point: [1/(n+1),2/(n+1).,...,n/(n+1)].
//*
void CALF(int n,double x[],double &f)
{
double kappa, objscale,p,h, c1,c2;
kappa = 1.0;
objscale = 100000000.0;
h = 1.0/(float(n)+1.0);
p = 1.0/objscale;
c1 = p*(h*h+2.0)/(h*h);
c2 = kappa*p/(h*h);
f=0.50*p*(x[0]*x[0]+x[n-1]*x[n-1]);
for(int i=0;i<n-1;i++)
f = f+0.50*p*pow((x[i]-x[i+1]),2);
for(i=0;i<n;i++)
f = f-c1*x[i]-c2*cos(x[i]);
}
//*-- Gradient
void CALG(int n,double x[],double g[])
{
double kappa, objscale,p,h, c1,c2;
kappa = 1.0;
objscale = 100000000.0;
h = 1.0/(float(n)+1.0);
p = 1.0/objscale;
c1 = p*(h*h+2.0)/(h*h);
c2 = kappa*p/(h*h);
g[0] = 2.0*p*x[0] - p*x[1] - c1 + c2*sin(x[0]);
for(int i=1;i<n-1;i++)
g[i] = -p*(x[i-1]-x[i]) + p*(x[i]-x[i+1]) - c1 + c2*sin(x[i]);
g[n-1] = 2.0*p*x[n-1] - p*x[n-2] - c1 + c2*sin(x[n-1]);
}
//*
//****************************************************************
//************************************************************
double DOIT(double m1[N],double m2[N]){
double sum=0;
for(int i=0;i<N;i++)
sum+=m1[i]*m2[i];
return sum;
}//DOIT
int wolf1(double x[],double work[],double g[],double alpha,double c1,double c2){
double f1,f2;
double temp[N];
CALF(N,x,f1);
for(int i=0;i<N;i++)
temp[i]=x[i]+alpha*work[i];
CALF(N,temp,f2);
double temp1=DOIT(g,work);
double temp2=-c1*alpha*temp1;
if((f1-f2)>=temp2)return 1;
else return 0;
}//wolf1
int wolf2(double x[],double work[],double g[],double alpha,double c1,double c2){
double ng[N];
double temp[N];
for(int i=0;i<N;i++)
temp[i]=x[i]+alpha*work[i];
CALG(N,temp,ng);
double temp1=DOIT(ng,work);
double temp2=c2*fabs(DOIT(g,work));
if(temp1<=temp2)return 1;
else return 0;
}//wolf2
void main()
{
double x[N],G[N],work[N];
double c1=0.1,c2=0.5;
double alpha=1;
double a=0,b=1000;
double temp,temp1,temp2,temp3,temp_x[N],temp_g[N];
int k=0;
for(int i=0;i<N;i++)
if(i%2==0)x[i]=1/(N+1);
else x[i]=1/(N+1);
CALG(N,x,G);
for(i=0;i<N;i++)
work[i]=-G[i];
CALF(N,x,temp1);
temp2=DOIT(G,work);
step2:
for(i=0;i<N;i++)
temp_x[i]=x[i]+alpha*work[i];
CALF(N,temp_x,temp);
if(wolf1(x,work,G,alpha,c1,c2))
goto step3;
else{
b=alpha;
alpha=a+(alpha-a)/(2*(1+(temp1-temp)/((alpha-a)*temp2)));
k++;
goto step2;
}
step3:
for(i=0;i<N;i++)
temp_x[i]=x[i]+alpha*work[i];
CALG(N,temp_x,temp_g);
temp3=DOIT(temp_g,work);
if(wolf2(x,work,G,alpha,c1,c2))
goto step4;
else{
a=alpha;
alpha=alpha+((alpha-a)*temp3)/(temp2-temp3);
temp1=temp;
temp2=temp3;
k++;
goto step2;
}
step4:
cout<<"迭带步数"<<k<<'\n';
cout<<"alpha:"<<alpha<<'\n';
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -