用黄金分割法求目标函数 f(x)=x*x-5*x+2 的最优解(C++)

来源:百度知道 编辑:UC知道 时间:2024/05/26 16:27:41
用黄金分割法求目标函数 f(x)=x*x-5*x+2 的最优解

在线= 谢谢了啊

试试我的程序吧,直接贴到某个地方就能用,百度的代码显示看起来不美观,凑合看吧,建议贴到程序里看方便一些,已经调试通过:
#include<iostream>
using namespace std;
const float EPS=0.000001;//定义常量
float f(float);

//定义函数f
float f(float x)
{
return x*x-5*x+2;
}

void main()
{
float a,b,x1,x2,f1,f2,t,eps;
cout<<"a=";cin>>a;
cout<<"b=";cin>>b;
cout<<"eps=";cin>>eps;
x1=a+0.382*(b-a);x2=a+0.618*(b-a);
f1=f(x1);f2=f(x2);

while (b-a>eps)//搜索精度循环节
{
t=f1-f2;
if (t>EPS) {a=x1;x1=x2;f1=f2;x2=a+0.618*(b-a);f2=f(x2);}

else if (t>=-EPS && t<=EPS) {a=x1;b=x2;x1=a+0.382*(b-a);x2=a+0.618*(b-a);f1=f(x1);f2=f(x2);}//函数值相等,两边区间均舍去

else {b=x2;x2=x1;f2=f1;x1=a+0.382*(b-a);f1=f(x1);}
}

cout<<"x*="<<(a+b)/2;
system ("pause");
}

#include "math.h&qu