作业帮 > 综合 > 作业

采用0.618法求在区间[0,1]内函数f (x)=x(x-1)2(x-2)3的最小值 vc++编程、、、谢~

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/07/09 01:18:54
采用0.618法求在区间[0,1]内函数f (x)=x(x-1)2(x-2)3的最小值 vc++编程、、、谢~
#include
using namespace std;
const float EPS=0.000001;//定义常量
float f(float);
//定义函数f
float f(float x)
{
return x*(x-1)^2*(x-2)^3;
}
void main()
{
float a,b,x1,x2,f1,f2,ε,eps;
couta;
coutb;
couteps;
x1=a+0.382*(b-a);x2=a+0.618*(b-a);
f1=f(x1);f2=f(x2);
while (b-a>eps)//搜索精度循环节
{
=f1-f2;
if (ε>EPS) {a=x1;x1=x2;f1=f2;x2=a+0.618*(b-a);f2=f(x2);}
else if (ε>=-EPS && ε
帮你改了一下,请看一下.
#include<iostream>
using namespace std;
const float EPS=0.000001;//定义常量
float f(float);
//定义函数f
float f(float x)
{
 return  x*(x-1)*(x-1)*(x-2)*(x-2)*(x-2);//这里的减号是全角字符,必须改为半角;还有符号“^”必须用于整型,无法用于浮点型.
}
void main()
{
 float a,b,x1,x2,f1,f2,alf,eps;//编译器认为ε是非法变量名,暂改名为alf,下同
 cout<<"a=0";cin>>a;
 cout<<"b=1";cin>>b;
 cout<<"eps=0.001";cin>>eps;
 x1=a+0.382*(b-a);x2=a+0.618*(b-a);
 f1=f(x1);f2=f(x2);
 while (b-a>eps)//搜索精度循环节
 {
    alf=f1-f2;//这里等号左边少了变量,是ε?暂时已经换成了alf了.
    if (alf>EPS) {a=x1;x1=x2;f1=f2;x2=a+0.618*(b-a);f2=f(x2);}
    else if (alf>=-1*EPS && alf<=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");
}