这个程序中有些数据类型转换的有问题,望大虾们解决!
#include <stdio.h>#include <math.h>
double ff(double x)
{
return 2*x*x+3*x*x-8*x+10;
}
/*此子程序完成x0->x1赋值*/
void fuzhi(double x0[],double x1[],int n)
{
int i;
for(i=0;i<n;i++)x1[i]=x0[i];
}
/* 功能:s方向,h步长,变量x的变化*/
void add(double x[],double h,double s[],int n)
{
int i;
for(i=0;i<n;i++) x[i]=h*s[i]+x[i];
}
/*进退法子程序(用于多维优化问题)*/
void jintui(double x[],double h0,double p[],double s[],int n)
{
double x1,x2,x3,y1,y2,y3,x0[10];
x1=0.0;y1=ff(x0);x2=x1+h0;
fuzhi(x,x0,n);add(x0,x2,s,n);y2=ff(x0);
if(y2>=y1)
{h0=-h0;x3=x1;y3=y1;x1=x2;
y1=y2;x2=x3;y2=y3;}
h0=2*h0;x3=x2+h0;
fuzhi(x,x0,n);add(x0,x3,s,n);y3=ff(x0);
while(y2>=y3)
{
x1=x2;y1=y2;x2=x3;y2=y3;
h0=2*h0;x3=x2+h0;
fuzhi(x,x0,n);add(x0,x3,s,n);y3=ff(x0);
}
if(h0<0.0) {p[0]=x3;p[1]=x1;}
else{p[0]=x1;p[1]=x3;}
}
/*黄金分割法子程序*/
void hjfg(double x[],double e,double s[],int n)
{
double h0=0.1,x1,x2,x3,y1,y2,y3,a,b,p[2],x0[10];
jintui(x,h0,p,s,n);
a=p[0];b=p[1];
x1=a+0.382*(b-a);fuzhi(x,x0,n);add(x0,x1,s,n);y1=ff(x0);
x2=a+0.618*(b-a);fuzhi(x,x0,n);add(x0,x2,s,n);y2=ff(x0);
while(b-a>e)
{
if(y1<y2){
b=x2;x2=x1;y2=y1;
x1=a+0.382*(b-a);fuzhi(x,x0,n);add(x0,x1,s,n);y1=ff(x0);
}
else{
a=x1;x1=x2;y1=y2;
x2=a+0.618*(b-a);fuzhi(x,x0,n);add(x0,x2,s,n);y2=ff(x0);
}
}
add(x,0.5*(a+b),s,n);
}
void main()
{
float x0[10],x1[10],e,total,ym,ss[10][10];
int k ,i,j,n;
printf("请输入:维数n,精度e:\n");
scanf("%d,%f",&n,&e);
printf("请输入:初始点:\n");
for (i=0;i<n;i++)
scanf ("%f",&x0[i]);
for (k=0;k<n;k++)
if (k=i) ss[i][k]=1.0;
else ss[i][k]=0.0;
do{
for (i=0;i<n;i++) x1[i]=x0[i];
for (i=0;i<n;i++) hjfg(x1,e,ss+i,n);
total=0.0;
for (i=0;i<n;i++)
total=(x1[i]-x0[i])*(x1[i]-x0[i])+total;
if(sqrt(total)<e)break;
for(i=0;i<n;i++) x0[i]=x1[i];
}while(1);
printf("目标函数最优解:\n");
for (i=0;i<n;i++)
printf ("x(%d)=%f",i+1,x1[i]);
printf ("\ny*=%f\n",ff(x1));
}