最优化方法一维搜索法C++程序

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

加步探索法#includeiostream#includemath.husingnamespacestd;doublefun(doublet){return(t*t*t-2*t+1);}doublemax(doublea,doubleb){if(ab)returna;elsereturnb;}doublemin(doublea,doubleb){if(ab)returnb;elsereturna;}doubleAddstep(double(*pfun)(doublet)){intk=0;doublet0=0,h=1,r=2,t,a=0,b=0;t=t0+h;do{if(fun(t)fun(t0)){h=r*h;t0=t;t=t0+h;k++;}else{if(k=0){h=-h;k++;}else{a=min(t0,t);b=max(t0,t);returna;returnb;}}}while(a=b);cout探索区间为:[min(t0,t),max(t0,t)]endl;}intmain(){Addstep(fun);return0;}对分法#includeiostream#includemath.husingnamespacestd;doublefun(doublet){return(t*t-3*t);}doubledfun(doublet){return(2*t-3);}voidDichotomous(double(*pfun)(doublet),double(*pdfun)(doublet)){intmaxflag=1000,k=1;doublea=-3,b=5,c,err=0.1,t;do{c=(a+b)/2;if(dfun(c)0){a=c;}else{if(dfun(c)0){b=c;}else{a=c;b=c;}}k++;}while(fabs(a-b)err&&kmaxflag);if(k=maxflag)coutendl对分法迭代失败!迭代次数为k=kendl;else{coutendl对分法迭代成功!迭代次数为k=k-1endl;cout迭代结果:近似根为root=tendl;cout函数值近似为:f(root)=fun(t)endl;}}intmain(){Dichotomous(fun,dfun);return0;}Newton切线法#includeiostream#includemath.husingnamespacestd;doublefun(doublet){return(t*t*t-2*t+1);}doubledfun(doublet){return(3*t*t-2);}voidNewtonIterative(double(*pfun)(doublet),double(*pdfun)(doublet)){intmaxflag=1000,k=1;doublet0=1,err=0.01,t;do{t0=t;t=t0-pfun(t0)/pdfun(t0);k++;}while(fabs(t-t0)err&&kmaxflag);if(k=maxflag)coutendl牛顿迭代失败!迭代次数为k=kendl;else{coutendl牛顿迭代成功!迭代次数为k=k-1endl;cout迭代结果:近似根为root=tendl;cout函数值近似为:f(root)=fun(t)endl;}}intmain(){NewtonIterative(fun,dfun);return0;}黄金分割法#includeiostream#includemath.husingnamespacestd;doublefun(doublet){return(t*t+2*t);}voidGoldensection(double(*pfun)(doublet)){intmaxflag=1000,k=1;doublea=-3,b=5,err=0.001,t,t1,t2;do{t1=a+0.618*(b-a);t2=b-0.618*(b-a);if(t1=t2){a=t2;b=t1;}else{if(t1t2){a=t2;}else{b=t1;}}k++;}while(fabs(a-b)err&&kmaxflag);if(k=maxflag)coutendl黄金分割法迭代失败!迭代次数为k=kendl;else{t=(a+b)/2;coutendl黄金分割法迭代成功!迭代次数为k=k-1endl;cout迭代结果:近似根为root=tendl;cout函数值近似为:f(root)=fun(t)endl;}}intmain(){Goldensection(fun);return0;}抛物线插值法#includeiostream#includemath.husingnamespacestd;doublefun(doublex){return(8*x*x*x-2*x*x-7*x+3);}doublemax(doublea,doubleb){if(ab)returna;elsereturnb;}doublemin(doublea,doubleb){if(ab)returnb;elsereturna;}voidParainterpolation(double(*pfun)(doublex)){doublea=0,b=2,err=0.001,x=0,x0=1,f,f0;do{x=((x0*x0-b*b)*fun(a)+(b*b-a*a)*fun(x0)+(a*a-x0*x0)*fun(b))/(2*((x0-b)*fun(a)+(b-a)*fun(x0)+(a-x0)*fun(b)));f0=fun(x0);f=fun(x);if(f=f0){a=min(x,x0);b=max(x,x0);x0=(a+b)/2;}else{if((fun(x)-f0)*(x-x0)0){b=max(x,x0);x0=min(x,x0);}else{a=min(x,x0);x0=max(x,x0);}}}while(fabs(x-x0)err);x=(x+x0)/2;cout迭代结果:近似根为root=xendl;cout函数值近似为:f(root)=fun(x)endl;}intmain(){Parainterpolation(fun);return0;}

1 / 6
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功