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