计算 f(x1,x2)=x^2+x1^2-x0*x1-10*x0-4*x1+60
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
double objf(double x[])
{double ff;
ff=x[0]*x[0]+x[1]*x[1]-x[0]*x[1]-10*x[0]-4*x[1]+60;
return(ff);
}
void jtf(double x0[],double h0,double s[],int n,double a[],double b[])
{int i;
double *x[3],h,f1,f2,f3;
for(i=0;i<3;i++)
x[i]=(double *)malloc(n*sizeof(double));
h=h0;
for(i=0;i
*(x[0]+i)=x0[i];
f1=objf(x[0]);
for(i=0;i
*(x[1]+i)=*(x[0]+i)+h*s[i];
f2=objf(x[1]);
if(f2>=f1)
{h=-h0;
for(i=0;i
*(x[2]+i)=*(x[0]+i);
f3=f1;
for(i=0;i
{*(x[0]+i)=*(x[1]+i);
*(x[1]+i)=*(x[2]+i);
}
f1=f2;
f2=f3;
}
for(;;)
{h=2*h;
for(i=0;i
*(x[2]+i)=*(x[1]+i)+h*s[i];
f3=objf(x[2]);
if(f2
else
{ for(i=0;i
{*(x[0]+i)=*(x[1]+i);
*(x[1]+i)=*(x[2]+i);
}
f1=f2;
f2=f3;
}
}
if(h<0)
for(i=0;i
{a[i]=*(x[2]+i);
b[i]=*(x[0]+i);
}
else
for(i=0;i
{a[i]=*(x[0]+i);
b[i]=*(x[2]+i);
}
for(i=0;i<3;i++)
free(x[i]);
}
double gold(double a[],double b[],double eps,int n,double xx[])
{int i;
double f1,f2,*x[2],ff,q,w;
for(i=0;i<2;i++)
x[i]=(double *)malloc(n*sizeof(double));
for(i=0;i
{*(x[0]+i)=a[i]+0.618*(b[i]-a[i]);
*(x[1]+i)=a[i]+0.382*(b[i]-a[i]);
}
f1=objf(x[0]);
f2=objf(x[1]);
do
{if(f1>f2)
{for(i=0;i
{b[i]=*(x[0]+i);
*(x[0]+i)=*(x[1]+i);
}
f1=f2;
for(i=0;i
*(x[1]+i)=a[i]+0.382*(b[i]-a[i]);
f2=objf(x[1]);
}
else
{ for(i=0;i
{a[i]=*(x[1]+i);
*(x[1]+i)=*(x[0]+i);}
f2=f1;
for(i=0;i
*(x[0]+i)=a[i]+0.618*(b[i]-a[i]);
f1=objf(x[0]);
}
q=0;
for(i=0;i
q=q+(b[i]-a[i])*(b[i]-a[i]);
w=sqrt(q);
}while(w>eps);
for(i=0;i
xx[i]=0.5*(a[i]+b[i]);
ff=objf(xx);
for(i=0;i<2;i++)
free(x[i]);
return(ff);
}
double oneoptim(double x0[],double s[],dou