在类中使用目标函数会产生错误的结果

时间:2018-12-03 12:10:48

标签: nlopt

我正在尝试将nlopt与在类内创建的目标函数一起使用,并且使用了Pointer to function to member function

中提供的解决方案

但是,我发现了一个我不理解的非常奇怪的行为。我创建了一个简单的示例来重现该问题。

#include <math.h>
#include <iostream>
#include <vector>
#include <nlopt.hpp>

using namespace std;

class MyClass
{
private:
    double *point;
    unsigned ndim;
public:
    MyClass(double *p,unsigned n) {point =    p; ndim = n; }
    ~MyClass() { }
    double myfunc(unsigned n, const double *x, double *grad);
};

double MyClass::myfunc(unsigned n, const double *x, double *grad)
{
    if (grad)
    {
        for (int i=0;i<n;i++){
            grad[i] = 2.*(x[i]-point[i]);
        }
    }    

    double sum = 0.;
    for (int i=0;i<n;i++){
        sum += (x[i] - point[i]) * (x[i] - point[i]);
    }
// here is the critical line
    cout << "n: " << n << "  " << x[0] << " " << x[1] << " :"  << endl;      
    return sum;
}


double wrapper(unsigned n, const double* x, double* grad, void* other) 
{
    reinterpret_cast<MyClass*>(other)->myfunc(n, x, grad);
}


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

    double p[] = {0.3,0.6};
    unsigned n = 2;
    MyClass ejemplo(p,n);


    nlopt::opt opt(nlopt::LD_MMA, n);
    opt.set_min_objective(wrapper, &ejemplo);
    opt.set_xtol_rel(1e-4);

    vector<double> x(2);
    x[0] = 1.234; x[1] = 5.678;
    double minf;
    nlopt::result result = opt.optimize(x, minf);
    cout << "found minimum at f(" << x[0] << "," << x[1] << ") = " << minf << endl;
    return 0;
}

如果我执行代码,则一切正常,但是,如果我注释该行

cout << "n: " << n << "  " << x[0] << " " << x[1] << " :"  << endl;    

然后结果是错误的。确实,如果我改写

cout << "n: " << n  <<  endl;     

然后我进入无限循环。或取出最后一个“:”会给出错误的结果。谁能解释我发生了什么事?

谢谢!

编辑:非常抱歉。我发现了错误。 return函数中缺少wrapper。问题解决了。无论如何,结果取决于印刷线仍然是很奇怪的。如果有人可以解释...

0 个答案:

没有答案