机仪学院 研1104班
郑生龙 1108020111
#include
#include
#define e 0.001
#define step 0.01
float f(float x)
{
float y=x*x-9*x;/*****输入目标函数******/
return(y);
}
/**********进退法*********/
find(float *v,float *b)
{
float x1,x2,x3,t,h;
float f1,f2,f3;
int n=0;
h=step;
x1=0;
x2=x1+h;f1=f(x1);f2=f(x2);
if(f2>f1)
{h=-h;
t=x2;
x2=x1;
x1=t;}
x3=x2+h;
f3=f(x3);
do { h=2*h;x1=x2;x2=x3;x3=x2+h;f1=f2;f2=f3;f3=f(x3);n=n+1;
}
while(f3
if(x1>x3)
{t=x1;x1=x3;x3=t;}
*v=x1;*b=x3;
return(n);
}
/*******二次插值法********/
chazhi(float *lmin)
{
float a,x4,b,x1,x2,x3,c1,c2;
float f1,f2,f3,f4,h;
int n=1;
h=step;
find(&a,&b);
x1=a;
x3=b;
x2=(x1+x3)/2;
f1=f(x1);
f2=f(x2);
f3=f(x3);
loop: c1=(f3-f2)/(x3-x2);
c2=((f2-f1)/(x2-x1)-c1)/(x2-x3);
x4=0.5*(x1+x3-c1/c2);
f4=f(x4);
if((f2-f4)/f2
{
/*****输出最小值******/
if(f2
{
*lmin=x2;}
else
{
*lmin=x4;}
}
else
if((x4-x2)*h>0)
{
if(f2>=f4)
{
x1=x2;
f1=f2;
x2=x4;
f2=f4;
n++;
goto loop;}
else
{
x3=x1;
f3=f1;
n++;
goto loop;}}
else
{
if(f2>=f4)
{
x3=x2;
f3=f2;
x2=x4;
f2=f4;
n++;
goto loop;}
else
{
x1=x4;
f1=f4;
n++;
goto loop;}}
return(n);/******返回迭代次数******/
}
/*********主函数*********/
main()
{
float a,b,x,min;int n1,n2;
n1=find(&a,&b); /******* 其中n1、n2为进退法与二次插值法的迭代次数 ****/ n2=chazhi(&x);
min=f(x);
printf("\n 范围是从%.3f到%.3f.",a,b); printf("\n 进退法迭代次数= %d.",n1); printf("\n 最小值是x= %.3f min= %.3f.",x,min);
printf("\n 二次插值法迭代次数= %d.",n2);
}
运行结果
机仪学院 研1104班
郑生龙 1108020111
#include
#include
#define e 0.001
#define step 0.01
float f(float x)
{
float y=x*x-9*x;/*****输入目标函数******/
return(y);
}
/**********进退法*********/
find(float *v,float *b)
{
float x1,x2,x3,t,h;
float f1,f2,f3;
int n=0;
h=step;
x1=0;
x2=x1+h;f1=f(x1);f2=f(x2);
if(f2>f1)
{h=-h;
t=x2;
x2=x1;
x1=t;}
x3=x2+h;
f3=f(x3);
do { h=2*h;x1=x2;x2=x3;x3=x2+h;f1=f2;f2=f3;f3=f(x3);n=n+1;
}
while(f3
if(x1>x3)
{t=x1;x1=x3;x3=t;}
*v=x1;*b=x3;
return(n);
}
/*******二次插值法********/
chazhi(float *lmin)
{
float a,x4,b,x1,x2,x3,c1,c2;
float f1,f2,f3,f4,h;
int n=1;
h=step;
find(&a,&b);
x1=a;
x3=b;
x2=(x1+x3)/2;
f1=f(x1);
f2=f(x2);
f3=f(x3);
loop: c1=(f3-f2)/(x3-x2);
c2=((f2-f1)/(x2-x1)-c1)/(x2-x3);
x4=0.5*(x1+x3-c1/c2);
f4=f(x4);
if((f2-f4)/f2
{
/*****输出最小值******/
if(f2
{
*lmin=x2;}
else
{
*lmin=x4;}
}
else
if((x4-x2)*h>0)
{
if(f2>=f4)
{
x1=x2;
f1=f2;
x2=x4;
f2=f4;
n++;
goto loop;}
else
{
x3=x1;
f3=f1;
n++;
goto loop;}}
else
{
if(f2>=f4)
{
x3=x2;
f3=f2;
x2=x4;
f2=f4;
n++;
goto loop;}
else
{
x1=x4;
f1=f4;
n++;
goto loop;}}
return(n);/******返回迭代次数******/
}
/*********主函数*********/
main()
{
float a,b,x,min;int n1,n2;
n1=find(&a,&b); /******* 其中n1、n2为进退法与二次插值法的迭代次数 ****/ n2=chazhi(&x);
min=f(x);
printf("\n 范围是从%.3f到%.3f.",a,b); printf("\n 进退法迭代次数= %d.",n1); printf("\n 最小值是x= %.3f min= %.3f.",x,min);
printf("\n 二次插值法迭代次数= %d.",n2);
}
运行结果