我是C++的新手,所以请原谅我的无知。我正在考虑使用Boost库来进行一维优化。我正在使用brent_find_minima函数,并查看了文档页这里。但是对于brent_find_minima函数的输入,需要给出另一个函数f。
使用它的示例显示为这里,但它们的函数只接受一个参数。例如,double f(double x){...},如果您想向f提供额外的参数,以便优化参数发生变化,例如double f(double x, int y, int z){...},y和z可以为相同的x更改函数f的结果,这是否可以在brent_find_minima阶段指定这一点?
考虑到我对C++非常陌生,任何演示如何做到这一点的例子/更改链接中给出的示例以接受超过一个参数将是非常有用的。
发布于 2014-03-01 21:04:35
如果要传递y,z的固定值,只需使用bind表达式:
double f(double x, int y, int z)
{ return (y*sin(x) + z + x * cos(x)); }
brent_find_minima(std::bind(f, _1, 3, 4), 3.0, 4.0, 20);它用3, 4来表示y, z。
如果不是这样的话,我不相信Brent的算法仍然是一个有效的方法。
看吧,住在Coliru
#include <iostream>
#include <sstream>
#include <string>
#include <functional> // functional
using namespace std::placeholders;
#include <boost/math/tools/minima.hpp>
double f(double x, int y, int z)
{ return (y*sin(x) + z + x * cos(x)); }
int main(int argc, char** argv)
{
typedef std::pair<double, double> Result;
// find a root of the function f in the interval x=[3.0, 4.0] with 20-bit precision
Result r2 = boost::math::tools::brent_find_minima(std::bind(f, _1, 3, 4), 3.0, 4.0, 20);
std::cout << "x=" << r2.first << " f=" << r2.second << std::endl;
return 0;
}
// output:
// x=3.93516 f=-0.898333发布于 2014-03-01 21:01:07
总是可以提供函子而不是函数。在这种情况下,指定的函数接受从brent_find_minimize函数调用的一个参数。如果您想要包含更多的参数,需要编写如下函子:
struct f
{
f(int y, int z) : _y(y), _z(z) { }
// you may need a copy constructor and operator= here too ...
double operator()(double x)
{
return _y*sin(x) + _z + x * cos(x);
}
int _y, _z;
};然后你就可以这样通过它:
Result r2 = boost::math::tools::brent_find_minima( f(10, 20), 3.0, 4.0, 20);希望这能有所帮助。
https://stackoverflow.com/questions/22119072
复制相似问题