资源描述
实 验 报 告
实验课程名称 机械优化设计
实验项目名称 共轭梯度法
年 级
专 业
学生姓名
学 号
实验时间: 2012 年11 月 2日
学生所在学院: 专业: 班级:
姓 名
学 号
实验组
实验时间
指导教师
成 绩
实验项目名称
共轭梯度法求函数极小值
1、 实验目的及要求:实验目的:掌握机械优化设计方法并能够理论联系实际地加以应用,任务是将课程所学的知识应用于实践,通过实际编写调试及运行程序加深理论知识的掌握并提高解决优化问题的能力。根据实验指导书的要求应能够独立的编写优化程序并在计算机上运行,学会判断结果及程序的正确性,学会建立机械优化设计的数学模型,合理选用优化方法,独立的解决机械优化设计的实际问题。
实验(或算法)原理:
共轭梯度法是共轭方向法中的一种,该方法中每一个共轭向量都是依赖与迭代点处的负梯度而构造出来。它通过梯度来寻找极小点。先通过一维搜索确定搜索区间,然后再通过共轭梯度法运用c语言编程求解。
实验硬件及软件平台:vs2010
实验步骤:
1. 确定所需求解的函数y=pow(x[0]+t*p[0],2)+25*pow(x[1]+t*p[1],2)
2. 确定搜索区间
3. 画出程序框图
4. 用c语言在vs2010上写出源代码
5. 运行程序
6. 检验试验结果,分析结果
实验内容(包括实验具体内容、算法分析、源代码等等):
本实验通过c语言编程,运用共轭梯度法求解函数y极小值;
程序框图
源程序
#include<stdio.h>
#include<math.h>
#define N 10
#define eps pow(10,-6)
double f(double x[],double p[],double t)
{
double s;
s=pow(x[0]+t*p[0],2)+25*pow(x[1]+t*p[1],2);
return s;
}
void sb(double *a,double *b,double x[],double p[])
{
double t0,t1,t,h,alpha,f0,f1;
int k=0;
t0=2.5; /*初始值*/
h=1; /*初始步长*/
alpha=2; /*加步系数*/
f0=f(x,p,t0);
t1=t0+h;
f1=f(x,p,t1);
while(1)
{
if(f1<f0)
{
h=alpha*h; t=t0;
t0=t1; f0=f1;
k++;
}
else
{
if(k==0)
{h=-h;t=t1;}
else
{
*a=t<t1?t:t1;
*b=t>t1?t:t1;
break;
}
}
t1=t0+h;
f1=f(x,p,t1);
}
}
double hjfg(double x[],double p[])
{
double beta,t1,t2,t;
double f1,f2;
double a=0,b=0;
double *c,*d;
c=&a,d=&b;
sb(c,d,x,p);
printf("\nx1=%lf,x2=%lf,p1=%lf,p2=%lf",x[0],x[1],p[0],p[1]);
printf("\n[a,b]=[%lf,%lf]",a,b);system("pause");
beta=(sqrt(5)-1.0)/2;
t2=a+beta*(b-a); f2=f(x,p,t2);
t1=a+b-t2; f1=f(x,p,t1);
while(1)
{
if(fabs(t1-t2)<eps)
break;
else
{
if(f1<f2)
{
t=(t1+t2)/2;
b=t2; t2=t1;
f2=f1; t1=a+b-t2;
f1=f(x,p,t1);
}
else
{
a=t1; t1=t2;
f1=f2;
t2=a+beta*(b-a);
f2=f(x,p,t2);
}
}
}
t=(t1+t2)/2;
return t;
}
void gtd()
{
double x[N],g[N],p[N],t=0,f0,mod1=0,mod2=0,nanda=0;
int i,k,n;
printf("请输入函数的元数值n=");
scanf("%d",&n);
printf("\n请输入初始值\n");
for(i=0;i<n;i++)
scanf("%lf",&x[i]);
f0=f(x,g,t);
g[0]=2*x[0]; g[1]=50*x[1];
mod1=sqrt(pow(g[0],2)+pow(g[1],2));
if(mod1>eps)
{
p[0]=-g[0]; p[1]=-g[1]; k=0;
while(1)
{
t=hjfg(x,p);
printf("\np1=%lf,p2=%lf,t=%lf",p[0],p[1],t);
x[0]=x[0]+t*p[0]; x[1]=x[1]+t*p[1];
g[0]=2*x[0]; g[1]=50*x[1];
/*printf("\nx1=%lf,x2=%lf,g1=%lf,g2=%lf",x[0],x[1],g[0],g[1]);*/
mod2=sqrt(pow(g[0],2)+pow(g[1],2));
if(mod2<=eps) break;
else
{
if(k+1==n)
{
g[0]=2*x[0]; g[1]=50*x[1];
p[0]=-g[0]; p[1]=-g[1]; k=0;
}
else
{
nanda=pow(mod2,2)/pow(mod1,2);
printf("\nnanda=%lf,mod=%lf",nanda,mod2);
p[0]=-g[0]+nanda*p[0];
p[1]=-g[1]+nanda*p[1];
mod1=mod2;
k++;
}
}
printf("\n--------------------------");
}
}
printf("\n最优解a为ax1=%lf,x2=%lf",x[0],x[1]);
printf("\n最终的函数值为a%lf",f(x,g,t));
}
main()
{
gtd();
}
实验结果与讨论:
运行截图
通过运行得到结果:x1=0.000001,x2=0时,ymin=0.000003
经验证结果正确
指导教师意见:
签名: 年 月 日
8
展开阅读全文