0.618算法的c++实现

#include 
   
   
    
    
#include 
    
    
     
     
using namespace std;
class Optimize
{
private:
	double a_, b_, namd_, miu_;
		double L_;
public:
	Optimize();
	Optimize(double a,double b,double L);
	void calculate();
	friend ostream& operator<<(ostream &os, Optimize &st)
	{
		os << st.a_ << " " << st.b_ << " " << st.namd_ << " " << st.miu_ << '\n';
		return os;
	}
};
double function(double x)
{
	return 2 *pow(x,2)- x - 1;
}
int main()
{
	Optimize example(-1.0, 1.0, 0.16);
	example.calculate();
	while (1);
	return 0;
}
Optimize::Optimize()
{
	a_= -1.0;
	b_ = 1.0;
	namd_ = 0.0;
	miu_ = 0.0;
	L_ = 0.16;
}
Optimize::Optimize(double a, double b, double L)
{
	a_ = a;
	b_ = b;
	L_ = L;
	namd_ = 0.0;
	miu_ = 0.0;
}
void Optimize::calculate()
{
	int k = 0;
	cout << 'k' << "    " << 'a' << "    " << 'b' << "    " 
		<< "namd" << "    " << "miu" << "    " << "f(namd)" << "    " << "f(miu)" << '\n';
	
	while (1)
	{
		k++;
	    namd_ = a_ + 0.382*(b_ - a_);
		miu_ = a_ + 0.618*(b_ - a_);
		cout << k << "    " << a_ << "    " << b_ << "    "
			<< namd_ << "    " << miu_ << "    " << function(namd_) << "" << function(miu_) << '\n';
		if ((b_ - a_) < L_)
			break;
		else
		{
			if (function(namd_) > function(miu_))
			{
				a_ = namd_;
				namd_ = miu_;
				miu_ = a_ + 0.618*(b_ - a_);
			}
			else
			{
				b_ = miu_;
				miu_ = namd_;
				namd_ = a_ + 0.382*(b_ - a_);
			}
		}

	}

}
    
    
   
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值