为brent_find_minima添加额外的粗鲁

adding additional arugments to brent_find_minima

本文关键字:添加 brent find minima      更新时间:2023-10-16

我对C++很陌生,所以请原谅我的无知。我正在考虑使用 Boost 库进行 1D 优化。我正在使用brent_find_minima函数,并查看了此处的文档页面。但是对于brent_find_minima函数的输入,需要给出另一个函数f

这里显示了使用它的示例,但它们的函数只接受一个参数。 double f(double x){...},如果您想提供额外的参数来f以便优化参数发生变化,例如 double f(double x, int y, int z){...} yz可以更改同一x的函数f结果,是否可以在brent_find_minima阶段指定它?

鉴于我对C++任何显示如何完成此操作的示例/更改链接中给出的示例以接受超过 1 个参数将非常有帮助。

如果要传递 y,z 的固定值,只需使用绑定表达式:

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

这对y, z来说已经过去了3, 4.

如果不是这样,我不相信布伦特的算法一定仍然是一种有效的方法。

科里鲁现场观看

#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

始终可以提供函子而不是函数。在这种情况下,指定的函数采用从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);

希望这有帮助。