gctl_optimization/example/ex3.cpp

69 lines
1.4 KiB
C++
Raw Normal View History

2024-09-10 20:04:47 +08:00
#include "../lib/optimization.h"
class TEST_FUNC : public gctl::lbfgs_solver
{
public:
TEST_FUNC();
~TEST_FUNC();
virtual double LBFGS_Evaluate(const gctl::array<double> &x, gctl::array<double> &g);
void Routine();
private:
gctl::array<double> m_x;
};
TEST_FUNC::TEST_FUNC()
{
m_x.resize(3, 0.0);
}
TEST_FUNC::~TEST_FUNC(){}
// test functions
// 3 = 3*x1 + x2 + 2*x3*x3
// 1 = -3*x1 + 5*x2*x2 + 2*x1*x3
// -12 = 25*x1*x2 + 20*x3
double TEST_FUNC::LBFGS_Evaluate(const gctl::array<double> &x, gctl::array<double> &g)
{
double f0,f1,f2,temp;
f0 = 3*x[0] + x[1] + 2*x[2]*x[2] - 3.012; //这里添加一点噪声
f1 = -3*x[0] + 5*x[1]*x[1] + 2*x[0]*x[2] - 1.04252;
f2 = 25*x[0]*x[1] + 20*x[2] + 12.12479;
temp = sqrt(f0*f0+f1*f1+f2*f2);
g[0] = 0.5*(6*f0+2*f1*(2*x[2]-3)+50*f2*x[1])/temp;
g[1] = 0.5*(2*f0+20*f1*x[1]+50*f2*x[0])/temp;
g[2] = 0.5*(8*f0*x[2]+4*f1*x[0]+40*f2)/temp;
return temp;
}
void TEST_FUNC::Routine()
{
gctl::lbfgs_para self_para = default_lbfgs_para();
self_para.m = 10;
self_para.past = 5;
self_para.residual = 1e-10;
//self_para.min_step = 1e-30;
//self_para.max_linesearch = 40;
//self_para.linesearch = gctl::LBFGS_LINESEARCH_BACKTRACKING_WOLFE;
set_lbfgs_para(self_para);
std::ofstream ofile("log.txt");
show_lbfgs_para(ofile);
double fx = LBFGS_Minimize(m_x, ofile);
ofile.close();
m_x.show();
return;
}
int main(int argc, char const *argv[])
{
TEST_FUNC test;
test.Routine();
return 0;
}