资源描述:
《机械优化设计编程(c语言)》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、反反复复二分法:#include#include"math.h"#defineE0.01voidmain(){floata,b,x,erfen(floata,floatb);printf("Entera,b");scanf("%f,%f",&a,&b);x=erfen(a,b);printf("x=%f",x);}floaterfen(floata,floatb){floatc,df(floatx);while(fabs(a-b)>E){c=(a+b)/2;if(df(c)==0)break;else{if(df(a)*df(c)<0)b=c;elsea
2、=c;}}returnc;}floatdf(floatx){return2*x-6;}黄金分割法:#include#include"math.h"#defineE0.001#defineH0.618voidmain(){floata,b,x;floatgoldcut(floata,floatb);printf("Entera,b");scanf("%f,%f",&a,&b);x=goldcut(a,b);printf("x*=%f",x);}floatgoldcut(floata,floatb){floatx1,x2,y1,y2;floatf(float
3、x);x2=a+H*(b-a);x1=a+b-x2;y1=f(x1);y2=f(x2);while(fabs(y1-y2)>=E){if(y1>y2){a=x1;x1=x2;y1=y2;x2=a+H*(b-a);y2=f(x2);}else{b=x2;x2=x1;y2=y1;x1=a+(1-H)*(b-a);y1=f(x1);}}return(x1+x2)/2;}floatf(floatx){returnx*x-6*x+2;}进退法:#include#include"math.h"voidmain(){floatx0,h,x1,jintui(floatx0,fl
4、oath);printf("Enterx0,h:");scanf("%f,%f",&x0,&h);x1=jintui(x0,h);printf("(%f,%f)",x0,x1);}floatjintui(floatx0,floath){floatf(floatx),x1,march(floatx0,floath);if(f(x0)>f(x0+h)){x1=march(x0,h);}else{h=-h;x1=march(x0,h);}returnx1;}floatf(floatx){returnx*x-6*x+2;}floatmarch(floatx0,floath){fl
5、oatx1=x0+h;while(f(x0)>f(x1)){x0=x1;h=2*h;x1=x0+h;}returnx1;}牛顿法:#include#include"math.h"#defineE0.0001voidmain(){floatx,x0,f(floatx);floatnewton(floatx);printf("Enterx");scanf("%f",&x);x0=newton(x);printf("(%f,%f)",x0,f(x0));}floatnewton(floatx){floatx1;floatf(floatx),df(floatx)
6、,ddf(floatx);while(fabs(df(x))>E){x1=x-df(x)/ddf(x);x=x1;}returnx;}floatf(floatx){returnx*x-6*x+2;}floatdf(floatx){return2*x-6;}floatddf(floatx){return0*x+2;}进退法与二分法结合:#include#include"math.h"#defineE0.001voidmain(){floatx0,h,x1,x2;floatjintui(floatx0,floath);floaterfen(floatx0,float
7、x1);printf("Enterx0,h");scanf("%f,%f",&x0,&h);x1=jintui(x0,h);printf("(%f,%f)",x0,x1);x2=erfen(x0,x1);printf("%f",x2);}floatjintui(floatx0,floath){floatx1;floatf(floatx);floatmarch(floatx0,floath);if(f(x0)>f(x0+h))x1=march(x0,h);else{h=