为brent_find_minima添加额外的粗鲁
adding additional arugments to brent_find_minima
我对C++很陌生,所以请原谅我的无知。我正在考虑使用 Boost 库进行 1D 优化。我正在使用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++任何显示如何完成此操作的示例/更改链接中给出的示例以接受超过 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);
希望这有帮助。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 将图像添加到资源文件夹UWP C++
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题