将对象信息传递给成本函数
问题就在这里。我使用 minpack 进行非线性优化。成本函数具有以下签名:
void cost_function(const int* n, const int* m,const double *p, double *x, int* iflag)
n - 初始点的大小 m - 函数向量的大小 p - 初始点 x - 函数向量
我有 for 循环,我在其中迭代对象数组。每个对象都包含优化函数的输入信息。
for(int counter = 0; i < num_of_objects; ++counter)
{
//get information from object
//call optimization function
lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}
但在成本函数中,我需要与当前对象相关的特定值。如果成本函数是类成员,则指针的类型将错误,并且无法将此指针传递给 lmdif1_。
所以现在我有一个临时解决方案,使用全局对象。
for(int counter = 0; i < num_of_objects; ++counter)
{
//get information from object
//call optimization function
global_obj = object;
lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}
然后cost_function使用这个全局对象来接收所需的信息。但这并不好。这个问题的正确解决方案是什么?谢谢。
Here is the problem. I use minpack for non-linear optimization. The cost function has the following signature:
void cost_function(const int* n, const int* m,const double *p, double *x, int* iflag)
n - size of initial point
m - size of function vector
p - initial point
x - function vector
I have for loop, where i iterate through the array of objects. Each object contain input information for optimization function.
for(int counter = 0; i < num_of_objects; ++counter)
{
//get information from object
//call optimization function
lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}
but in cost function i need particular values connected with current object. If cost function would be a class member, then the pointer will have wrong type, and it will be impossible to pass this pointer to lmdif1_.
So now i have a temporary solution, using global object.
for(int counter = 0; i < num_of_objects; ++counter)
{
//get information from object
//call optimization function
global_obj = object;
lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}
Then cost_function uses this global object to recieve needed information. But it's not good. What is the right solution for this problem? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这些
m
、n
、fvec
数组可以是类成员,您可以使用offsetof
宏来恢复班级的地址。 (有关如何执行此操作,请阅读非标准container_of 的说明 宏
)
如果它们是动态分配的,那就更难了,但是您可以在缓冲区中分配额外的空间,并将指向您的类的指针放在实际数组数据的前面。
If those
m
,n
,fvec
arrays can be class members, you could maybe use theoffsetof
macro to recover the address of the class. (For how to do that, read this explanation of the non-standardcontainer_of
macro)If they're dynamically allocated, it's harder, but you could allocate extra space in the buffer, and put a pointer to your class in front of the actual array data.