Bill Harber Bill Harber - 3 months ago 7
C++ Question

How to adjust a function

i am trying to use in C++ the algorithm of Nelder-Mead to minimize a function. I don't understand why this code doesn't compile.

#include <iostream>
#include "/home/user/CppNumericalSolvers/include/cppoptlib/meta.h"
#include "/home/user/CppNumericalSolvers/include/cppoptlib/problem.h"
#include "/home/user/CppNumericalSolvers/include/cppoptlib/solver/neldermeadsolver.h"


template<typename Ta>
class AB : public cppoptlib::Problem<Ta> {
public:
AB(int aa) : a(aa){}
using typename cppoptlib::Problem<Ta>::TVector;
//int a = 250;
Ta value(const TVector &x) {
return (1 - x[0]) * (1 - x[0]) + a * (x[1] - x[0] * x[0]) * (x[1] - x[0] * x[0]);
}



};



void test(){

typedef AB<double> TAB;
TAB f(250);
// choose a starting point
Eigen::VectorXd x(2); x << -1, 2;



// choose a solver
cppoptlib::NelderMeadSolver<TAB> solver;
// and minimize the function
solver.minimize(f, x);
// print argmin
std::cout << "argmin " << x.transpose() << std::endl;
std::cout << "f in argmin " << f(x) << std::endl;


}




int main(int argc, char const *argv[]) {

test();


return 0;
}


Andwhen i compile i received this :

essai.cpp: In constructor ‘AB<Ta>::AB(int)’:
essai.cpp:10:18: error: class ‘AB<Ta>’ does not have any field named ‘a’
AB(int aa) : a(aa){}
^
essai.cpp: In member function ‘Ta AB<Ta>::value(const typename cppoptlib::Problem<Ta>::TVector&)’:
essai.cpp:14:44: error: ‘a’ was not declared in this scope
return (1 - x[0]) * (1 - x[0]) + a * (x[1] - x[0] * x[0]) * (x[1] - x[0] * x[0]);
^


If you have some ideas it will help me a lot because right now i have no ideas how to do this !

Thanks for your help !

Answer

Here is the code to create a constructor to input a given value to object of AB in function test

  template<typename Ta>
  class AB : public cppoptlib::Problem<Ta> 
  {
    int a;
   public:
    using typename cppoptlib::Problem<Ta>::TVector;
    AB(int num):a(num)
    {}
    Ta value(const TVector &x)
    {
      return   (1 - x[0]) * (1 - x[0]) + a * (x[1] - x[0] * x[0]) * (x[1] - x[0] * x[0]); 
    }
  };


  void test()
  {

    typedef AB<double> TAB;
    TAB f(25); //initializes a with 25
Comments