2016-08-07 5 views
-4

Я пытаюсь использовать в C++ алгоритм Nelder-Mead для минимизации функции. Я не понимаю, почему этот код не компилируется.Как настроить функцию

#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 я компиляции я получил это:

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]); 
              ^

Если у вас есть какие-то идеи, это поможет мне много, потому что сейчас у меня нет идеи, как это сделать!

Благодарим за помощь!

+2

Так дайте 'AB' конструктор, который принимает' int' параметр, и инициализировать 'Ā' из этот параметр. Это C++ 101. –

+0

Спасибо за ваш ответ, у вас есть пример? Потому что я никогда не делаю конструктора класса в основном только с * .cpp и * .hpp файлами. Большое спасибо ! –

+0

Просто добавьте эту строку в 'class AB' после' public': 'AB (int aa): a (aa) {}'. Затем в 'test', объявите' f' следующим образом: 'TAB f (250);' Ничем не отличается, определяете ли вы класс в файле заголовка или в исходном файле. –

ответ

0

Вот код, чтобы создать конструктор для ввода заданного значения объекта АВ в тесте функции

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 
+0

Спасибо вам большое! –

Смежные вопросы