机械优化设计黄金分割法 外推法(2)
时间:2026-01-17
时间:2026-01-17
1.外推法
源程序:
#include<stdio.h> #include<math.h> #define R 0.01
double fun(double x) { double m; m=x*x-10*x+36; return m; }
void main() {
double h0=R,y1,y2,y3,x1,x2,x3,h; x1=0;h=h0;x2=h;
y1=fun(x1);y2=fun(x2); if(y2>y1) {h=-h; x3=x1; y3=y1; x1=x2; y1=y2; x2=x3; y2=y3; }
x3=x2+h;y3=fun(x3); while(y3<y2) {h*=2.0; x1=x2; y1=y2; x2=x3; y2=y3; x3=x2+h; y3=fun(x3); } printf("fun(%f)=%f,fun(%f)=%f,fun(%f)=%f\n",x1,y1,x2,y2,x3,y3); }
运行过程及结果: fun(2.560000)=16.953600, fun(5.120000)=11.014400,
fun(10.240000)=38.457600
2.黄金分割法
源程序:
#include<stdio.h> #include<math.h>
#define f(x) x*x*x*x-5*x*x*x+4*x*x-6*x+60
double hj(double *a,double *b,double e,int *n) { double x1,x2,s;
if(fabs((*b-*a)/(*b))<=e) s=f((*b+*a)/2); else {
x1=*b-0.618*(*b-*a); x2=*a+0.618*(*b-*a); if(f(x1)>f(x2)) *a=x1; else *b=x2; *n=*n+1; s=hj(a,b,e,n); }
return s; }
void main() { double s,a,b,e,m; int n=0;
printf("输入a,b值和精度e值\n"); scanf("%lf %lf %lf",&a,&b,&e); s=hj(&a,&b,e,&n); m=(a+b)/2;
printf("a=%lf,b=%lf,s=%lf,m=%lf,n=%d\n",a,b,s,m,n); }
上一篇:平翘舌音练习材料大全
下一篇:电化学理论(李狄)课后答案解析