黄金分割法.cpp

来自「最优化实验中的 WOLF 算法 黄金分割法 平分法程序」· C++ 代码 · 共 41 行

CPP
41
字号

//黄金分割法

#include<math.h>
#include<iostream.h>
#include<string.h>
#include<iomanip.h>

double F(double x)
{
	double f;
	f=pow(x,2)-x+2;
	return f;
}

int main()
{
	cout<<"迭代次数"<<setw(10)<<" [ a    ,    b ] "<<setw(10)<<"   x1            x2 "<<setw(10)<<"      f1            f2  "<<" |b-a|<e "<<endl;
	int i=0;
	double low=-1,high=3;
	double x1,x2;
	double e=0.32;
	double f1,f2;
	do{
		cout<<i++<<setw(10)<<low<<','<<setw(10)<<high<<" ";
		x1=low+0.382*(high-low);
		x2=low+0.618*(high-low);
		f1=F(x1);
		f2=F(x2);
		if(f1<f2)high=x2;
		else low=x1;
		cout<<setw(10)<<x1<<" , "<<setw(10)<<x2;
		cout<<setw(10)<<f1<<" , "<<setw(10)<<f2;
		if(fabs(high-low)>e)cout<<"   否";
		else cout<<"   是";
		cout<<endl;
	}while(fabs(high-low)>e);
		cout<<"!!press enter enter key to end!!"<<endl;
	cin.get();
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?