如何使用提升二分?

Mar*_*are 5 c++ boost

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

所以这就是我认为它应该如何运作但是从来没有看起来我似乎也错了.好的,所以我想用:

template <class F, class T, class Tol>
 std::pair<T, T> 
 bisect(
    F f, 
    T min, 
    T max, 
    Tol tol);
Run Code Online (Sandbox Code Playgroud)

这里,但我的问题是宽容,因为我不知道如何正确设置.我试过了

double value = boost::math::tools::eps_tolerance<double>(0.00001);
Run Code Online (Sandbox Code Playgroud)

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

谢谢 !

Kar*_*nek 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...
Run Code Online (Sandbox Code Playgroud)

编辑:或者,这是你如何使用自定义功能:

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());
Run Code Online (Sandbox Code Playgroud)