c++ - 如何使用 boost 二分法?

标签 c++ boost

昨天我在另一个 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?

谢谢!

最佳答案

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

关于c++ - 如何使用 boost 二分法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8245909/

相关文章:

c++ - 未显示 libstdc++-v3 中的 GCC 源代码修改

c++ - std::pair 中有超过 2 个变量

c++ - 如何计算 C++ 中正态分布的 CDF 概率?

c++ - 从 https ://github. com/boostorg/boost.git 在 Windows 上构建 Boost

c++ - 在 C++ 中,如何从声明中获取任意函数的类型?

c++ - std::vector 内部结构

c++ - 检索具有多个重叠 I/O 请求的缓冲区

c++模板参数编译器无法推断

c++ - 将 QString 转换为 QJsonArray

c++ - 无法使用 boost asio 专门绑定(bind)到网络端口