Hello, I have pasted my code and the output during runtime below. I am
trying to use the global optimization algorithm nlopt::GD_STOGO. I don't
understand why I am getting the  "nlopt failure" error. Could you please
help me. Thank you.



CODE:

// Standard library headers
#include <exception>
#include <iostream>
#include <vector>

// NLopt headers
#include "nlopt.hpp"

double f( const std::vector<double> &x, std::vector<double> &grad, void*
f_data )
{
    // Calculate gradient.
    if( grad.size() != 0 )
    {
        grad[0] = -1;
        grad[1] = 1;
    }

    static int iteration = 0;
    double cost = -x[0] + x[1];

    std::cout << "x = [" << x[0] << ", " << x[1] << "]" << std::endl;
    std::cout << "iteration  " << ++iteration << " cost " << cost <<
std::endl;
    return cost;
};

int main()
{
    try
    {
        nlopt::opt obj( nlopt::GD_STOGO, 2 );

        const std::vector<double> lb{ -3, -3 };
        const std::vector<double> ub{ 3, 3 };

        obj.set_lower_bounds( lb );
        obj.set_upper_bounds( ub );

        obj.set_min_objective( f, NULL );

        obj.set_maxeval( 10 );

        std::vector<double> x{ 0, 0 };

        double opt_f;
        nlopt::result r = obj.optimize( x, opt_f );

        std::cout << "[RESULT]: (" << x[0] << ", " << x[1] << ")" <<
std::endl;
    catch( std::exception & e )
    {
        std::cerr << "[ERROR]: " << e.what() << std::endl;
    }

    return 0;
}

OUTPUT AT RUNTIME:

x = [0, 0]
iteration  1 cost 0
x = [1, -1]
iteration  2 cost -2
x = [2, -2]
iteration  3 cost -4
x = [3, -3]
iteration  4 cost -6
x = [0, -1.8]
iteration  5 cost -1.8
x = [0.424264, -2.22426]
iteration  6 cost -2.64853
x = [0, 1.8]
iteration  7 cost 1.8
x = [0.424264, 1.37574]
iteration  8 cost 0.951472
x = [1.27279, 0.527208]
iteration  9 cost -0.745584
x = [2.27279, -0.472792]
iteration  10 cost -2.74558
[ERROR]: nlopt failure
_______________________________________________
NLopt-discuss mailing list
NLopt-discuss@ab-initio.mit.edu
http://ab-initio.mit.edu/cgi-bin/mailman/listinfo/nlopt-discuss

Reply via email to