⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dqdrtic.cpp

📁 共轭梯度的几种方法对标准函数的测试结果比较 附比较结果
💻 CPP
字号:

#include<iostream.h>
#define N 5
//************************************************************          
                                                                      
 
//cF51                          DQDRTIC                              
//*                             
//*     Initial point x0=[3,3,3...,3]             
//
void CALF(int n,double x[N],double &f){
      double c,d;
      
      c=100.0;
      d=100.0;
      
      f=0.0;
      for(int i=0;i<n-2;i++)
        f=f+(x[i]*x[i]+c*x[i+1]*x[i+1]+d*x[i+2]*x[i+2]);
}
      
//*-- Gradient 
void CALG(int n,double x[N],double g[N]){  
      double c,d;
      
      c=100.0;
      d=100.0;
      g[0]=2.0*x[0];
      g[1]=2.0*c*x[1]+2.0*x[1];
      
      for(int i=2;i<n-2;i++)
        g[i]=2.0*(1.0+d+c)*x[i];
      
      g[n-2]=2.0*(c+d)*x[n-2];          
      g[n-1]=2.0*d*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*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;
	int k=0;
	for(int i=0;i<N;i++)
		if(i%2==0)x[i]=3;
			else x[i]=3;
   CALG(N,x,G);
	for(i=0;i<N;i++)
		work[i]=-G[i];
	wolf1(x,work,G,alpha,c1,c2);
step2:
	if(wolf1(x,work,G,alpha,c1,c2)&&wolf2(x,work,G,alpha,c1,c2)){
	for(i=0;i<N;i++)
		   x[i]=x[i]+alpha*work[i];
	goto step5;}
	if(wolf1(x,work,G,alpha,c1,c2)==0){
		k++;
		goto step3;}
	if(wolf2(x,work,G,alpha,c1,c2)==0){
		k++;
		goto step4;}
step3:
	b=alpha;
	alpha=(a+alpha)/2;
	goto step2;
step4:
	a=alpha; 
	alpha=(2*alpha)>(alpha+b)/2?(alpha+b)/2:(2*alpha);
	goto step2;
step5:
	cout<<"迭带步数"<<k<<'\n';
	cout<<"alpha:"<<alpha<<'\n';

}



    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -