k=1;
while (abs(r1-r2)>=0.1)
if y1
二、进退法、0.618法的 C 语言程序设计
例1 设 f(x)=x^2-2*x+4 ,试确定初始搜索区间,并输出迭代次数
main()
{int n=0;
float t,h,a,b,c,d,f1,f2;
printf(“t,h:”);
scanf(“%f,%f”,&t,&h);
f1=t*t-2*t+4;
if((t+h)*(t+h)-2*(t+h)+4<=f1)
{c=t+h;f2=c*c-2*c+4;}
else
{h=-h;c=t+h; f2=c*c-2*c+4;}
while(f2<=f1)
{h=2*h;d=t;t=c;f1=f2;c=t+h; f2=c*c-2*c+4;n=n+1;}
if(c<=d)
{a=c;b=d;}
else
{a=d;b=c;}
printf(“[a,b]=[%.2f,%f]\n”,a,b);
printf(“n=%d\n”,n);
}
运行情况如下:
(1)t,h:0,0.05
[a,b]=[0.35,1.55]
n=4
(2) t,h:-1.0,0.02
[a,b]=[0.26,4.10]
n=7
(3)t,h:-100,0.01
[a,b]=[-59.05,63.83]
n=13
例2 用0.618法求 f(x)=8x^3-2*x^2-7*x+3 的局部最优解.允许误差ε=0.0001 ,初始点
设为 x0=0 ,初始步长 h=1 .
#include“math.h”
float f(x)
float x;
float y;
{y=((8.0*x-2.0)*x-7.0)*x+3.0;
return(y);
}
main()
{int n=0;
float t,h,a,b,c,d,x0,f0,f1,f2,fc,fd;
printf(“t,h:”);
scanf(“%f,%f”,&t,&h);
f1=f(t);
if (f(t+h)<=f1)c=t+h;
else{h=-h;c=t+h;}
f2=f(c);
while(f2<=f1)
{d=t;t=c;f1=f2;c=t+h;f2=f(c);}
if(c<=d){a=c;b=d;}
else{a=d;b=c;}
c=a+0.382*(b-a);fc=f(c);d=a+0.618*(b-a);fd=f(d);
do
{if (fc>=fd) {a=c;c=d;fc=fd;d=a+0.618*(b-a); fd=f(d);}
else {b=d;d=c;fd=fc;c=a+0.382*(b-a);fc=f(c);}
n++;
}
while (b-a>0.0001);
x0=(a+b)/2.0;f0=f(x0);
pintf(“n=%d,x0=%7.4f,f0=%7.4f\n”,n,x0,f0);
}
运行情况如下:
t,h:0,1.0
n=21,xo=0.6298,f0=-0.2034.