Nic*_*las 2 c++ newtons-method stdbind c++11 std-function
我尝试在多元函数上尝试我的牛顿方法片段并使用std::bind和std::function。但我被一个错误困住了
错误:请求从 'std::_Bind_helper&, int>::type {aka std::_Bind, int))(double, double, double)>}' 转换为非标量类型 'std::function'
此错误消息是什么意思,我应该如何修复我当前的代码?
#include <iostream>
#include<functional>
#include<cmath>
double newton(std::function<double(double)> F, std::function<double(double)> f,
double x=0, int maxiter=1000, double epsilon=0.001)
{
int n = 0;
while((n < maxiter) && (fabs(F(x)) > epsilon))
{
x = x - F(x) / f(x);
n++;
}
return x;
}
// I'd like to fix x and z at 1 and 2 and find root for y
double ftest(double x, double y, double z)
{
return x * x + (y * y - 2 * y - 4) + z * z;
}
// Partial derivative of ftest with regards to y
double ftest1(double y)
{
return 2 * y - 2;
}
int main()
{
using namespace std::placeholders;
std::function<double(double)> F = std::bind(ftest, 1, _2, 2);
std::function<double(double)> f = ftest1;
std::cout << newton(F, f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题:
std::function<double(double)> F = std::bind(ftest, 1, _2, 2);
Run Code Online (Sandbox Code Playgroud)
那F是一个接受 type 单个参数的函数double,但您的绑定表达式涉及_2- 它指的是传递给bind()返回的函数对象的第二个参数。即第二个论点。基本上,您正在构建这个函数对象,大致如下:
struct {
template <class T, class U>
auto operator()(T, U arg) {
return ftest(1, arg, 2);
}
};
Run Code Online (Sandbox Code Playgroud)
该对象有两个参数。std::function<double(double)>不允许这样做 - 它要求您的可调用对象允许单个参数。
简单的修复是修复占位符:
std::function<double(double)> F = std::bind(ftest, 1, _1, 2);
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,根本不使用bind()而更喜欢 lambda:
std::function<double(double)> F = [](double y) { return ftest(1, y, 2); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2974 次 |
| 最近记录: |