#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_);
}
}
}
}
0.618算法的c++实现
最新推荐文章于 2021-05-18 05:10:25 发布