nlopt
nlopt copied to clipboard
std::runtime_error when using GD_STOGO
I try to use the StoGo algorithm in NLOPT to optimize my objective function, but this algorithm always throw std::runtime_error(NLOPT_FAILURE). In order to verify the correctness of the code, I wrote a very simple example
#include <iostream>
#include <vector>
#include <nlopt.hpp>
double loss_fun(std::vector<double> const &x,std::vector<double> &grad,void *const data) {
if(!grad.empty()) {
grad[0]=2*x[0];
grad[1]=2*x[1];
}
double loss=x[0]*x[0]+x[1]*x[1];
return loss;
}
int main() {
nlopt::opt opter(nlopt::GD_STOGO,2);
opter.set_max_objective(loss_fun,nullptr);
opter.set_lower_bounds(0.0);
opter.set_upper_bounds(1.0);
opter.set_xtol_abs(1e-8);
opter.set_maxtime(1.0);
std::vector<double> x={0.5,0.5};
double loss_global=1.0;
nlopt::result res=opter.optimize(x,loss_global);
std::cout<<x[0]<<' '<<x[1]<<' '<<loss_global<<std::endl;
return 0;
}
This code maximizes the objective function $Loss=x_0^2+x_1^2$. Obviously, the maximum value is obtained when $x_0=1, x_1=1$. This code can get the correct result using most of the optimization algorithms, but it still reports an error when using StoGo. I'm not sure if there is a bug in my code.
My system is Ubuntu22 LTS, install NLopt by apt install libnlopt-cxx-dev,
and I use g++ -lnlopt_cxx -lm to compile this program.