1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <Eigen/Core>
#include <iostream>
#include <LBFGS.h>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using namespace LBFGSpp;
class Rosenbrock
{
private:
int n;
public:
Rosenbrock(int n_) : n(n_) {}
double operator()(const VectorXd& x, VectorXd& grad)
{
double fx = 0.0;
for(int i = 0; i < n; i += 2)
{
double t1 = 1.0 - x[i];
double t2 = 10 * (x[i + 1] - x[i] * x[i]);
grad[i + 1] = 20 * t2;
grad[i] = -2.0 * (x[i] * grad[i + 1] + t1);
fx += t1 * t1 + t2 * t2;
}
assert( ! std::isnan(fx) );
return fx;
}
};
int main()
{
LBFGSParam<double> param;
LBFGSSolver<double, LineSearchBracketing> solver(param);
for( int n=2; n <= 16; n += 2 )
{
std::cout << "n = " << n << std::endl;
Rosenbrock fun(n);
for( int test=0; test < 1024; test++ )
{
VectorXd x = VectorXd::Random(n);
double fx;
int niter = solver.minimize(fun, x, fx);
assert( ( (x.array() - 1.0).abs() < 1e-4 ).all() );
}
std::cout << "Test passed!" << std::endl << std::endl;
}
return 0;
}
|