如何使用提升二分?

时间:2011-11-23 16:44:53

标签: c++ boost

昨天我遇到了另一个提升功能的问题,但幸运的是你们帮助我解决了这些问题。今天我需要知道如何正确使用二分函数。

所以这就是我认为它应该如何运作但是从来没有像现在这样我也错了。好的,我想用:

template <class F, class T, class Tol>
 std::pair<T, T> 
 bisect(
    F f, 
    T min, 
    T max, 
    Tol tol);

来自here,但我的问题是容忍,因为我不知道如何正确设置。我试过了

double value = boost::math::tools::eps_tolerance<double>(0.00001);

以及如何在找到二分时返回值?结果应该是函数中的std :: pair数字对,之后只计算min + max / 2吗?

谢谢!

2 个答案:

答案 0 :(得分:9)

这是bisect的示例用法。考虑求解等式x^2 - 3x + 1 = 0

struct TerminationCondition  {
  bool operator() (double min, double max)  {
    return abs(min - max) <= 0.000001;
  }
};

struct FunctionToApproximate  {
  double operator() (double x)  {
    return x*x - 3*x + 1;  // Replace with your function
  }
};

// ...
using boost::math::tools::bisect;
double from = 0;  // The solution must lie in the interval [from, to], additionally f(from) <= 0 && f(to) >= 0
double to = 1;
std::pair<double, double> result = bisect(FunctionToApproximate(), from, to, TerminationCondition());
double root = (result.first + result.second) / 2;  // = 0.381966...

编辑:或者,您可以将它与自定义函数一起使用:

double myF(double x)  {
  return x*x*x;
}

double otherF(double x)  {
  return log(abs(x));
}

// ...
std::pair<double, double> result1 = bisect(&myF, from, to, TerminationCondition());
std::pair<double, double> result2 = bisect(&otherF, 0.1, 1.1, TerminationCondition());

答案 1 :(得分:0)

请注意,bisect还支持lambda:

using boost::math::tools::bisect;
auto root = bisect
(
    [](double x){return x;},
    -1.0, 1.0,
    [](double l, double r){return abs(l-r) < 1e-8;}
);