如何使用升压等分

How to use boost bisection?

本文关键字:何使用      更新时间:2023-10-16

昨天我遇到了另一个boost函数的问题,但幸运的是你们帮我解决了它们。今天我需要知道如何正确使用分割函数。

所以这就是我认为它应该如何工作,但从来没有少,似乎我得到这个也错了。所以我想使用:

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

从这里,但我的问题是宽容,因为我不知道如何设置正确的。我试着

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

和我如何返回值时,二分已找到?结果应该是一对数字作为std::pair在函数中,之后只是计算min+max/2?

谢谢!

这是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...

EDIT:或者,您可以将其与自定义函数一起使用:

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());

注意bisect也支持lambdas:

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;}
);