【发布时间】:2016-11-04 14:49:37
【问题描述】:
我尝试在多元函数上尝试牛顿方法的 sn-p 并使用 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;
}
【问题讨论】:
-
_2看起来应该是_1。其次,您是否考虑过不使用std::bind,而只使用lambda?[](double y){ return ftest(1,y,2); }在我看来比bind干净。
标签: c++ c++11 std-function newtons-method stdbind