《最优化方法一维搜索法C++程序(共6页).doc》由会员分享,可在线阅读,更多相关《最优化方法一维搜索法C++程序(共6页).doc(6页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、精选优质文档-倾情为你奉上加步探索法#include#includeusing namespace std;double fun(double t)return (t*t*t-2*t+1);double max(double a,double b)if(ab)return a;else return b;double min(double a,double b)if(ab)return b;else return a;double Addstep(double(*pfun)(double t)int k=0;double t0=0,h=1,r=2,t,a=0,b=0;t=t0+h;doif(f
2、un(t)fun(t0)h=r*h;t0=t;t=t0+h;k+;elseif(k=0)h=-h;k+; elsea=min(t0,t);b=max(t0,t);return a;return b;while(a=b);cout 探索区间为:min(t0,t),max(t0,t)endl;int main()Addstep(fun);return 0;对分法#include#includeusing namespace std;double fun(double t)return (t*t-3*t);double dfun(double t)return (2*t-3);void Dichot
3、omous(double(*pfun)(double t),double (*pdfun)(double t)int maxflag=1000,k=1;double a=-3,b=5,c,err=0.1,t;doc=(a+b)/2;if(dfun(c)0)b=c;elsea=c;b=c;k+;while(fabs(a-b)err&k=maxflag)coutendl对分法迭代失败!迭代次数为k=kendl;elsecoutendl 对分法迭代成功!迭代次数为k=k-1endl;cout迭代结果:近似根为root=tendl;cout 函数值近似为:f(root)=fun(t)endl;int
4、main()Dichotomous(fun,dfun);return 0;Newton切线法#include#includeusing namespace std;double fun(double t)return (t*t*t-2*t+1);double dfun(double t)return (3*t*t-2);void NewtonIterative(double(*pfun)(double t),double (*pdfun)(double t)int maxflag=1000,k=1;double t0=1,err=0.01,t;dot0=t;t=t0-pfun(t0)/pdfu
5、n(t0);k+;while(fabs(t-t0)err&k=maxflag)coutendl 牛顿迭代失败!迭代次数为k=kendl;elsecoutendl 牛顿迭代成功!迭代次数为k=k-1endl;cout 迭代结果:近似根为root=tendl;cout 函数值近似为:f(root)=fun(t)endl;int main()NewtonIterative(fun,dfun);return 0;黄金分割法#include#includeusing namespace std;double fun(double t)return (t*t+2*t);void Goldensection
6、(double(*pfun)(double t)int maxflag=1000,k=1;double a=-3,b=5,err=0.001,t,t1,t2;dot1=a+0.618*(b-a);t2=b-0.618*(b-a);if(t1=t2)a=t2;b=t1;else if(t1err&k=maxflag)coutendl黄金分割法迭代失败!迭代次数为k=kendl;elset=(a+b)/2;coutendl 黄金分割法迭代成功!迭代次数为k=k-1endl;cout 迭代结果:近似根为root=tendl;cout 函数值近似为:f(root)=fun(t)endl;int mai
7、n()Goldensection(fun);return 0;抛物线插值法#include#includeusing namespace std;double fun(double x)return (8*x*x*x-2*x*x-7*x+3);double max(double a,double b)if(ab)return a;else return b;double min(double a,double b)if(ab)return b;else return a;void Parainterpolation(double(*pfun)(double x)double a=0,b=2,e
8、rr=0.001,x=0,x0=1,f,f0;dox=(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); elsea=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;int main()Parainterpolation(fun);return 0;专心-专注-专业