Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c++ - How to use boost bisection?

Yesterday I had problems with another boost functions but luckily you guys helped me to solve them. Today I would need to know how to use bisection function properly.

So here is how I think it should work but never the less it seems that I'm getting this also wrong. Okay so I would like to use:

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

from here but my problem is with tolerance because I don't know how to set it right. I've tried

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

and how to I return the value when the bisection has found ? Should the result be pair of numbers as std::pair in the function and after that just calculate min+max/2?

Thanks !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an example use of bisect. Consider solving the equation 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: Alternatively, this is how you can use it with custom functions:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...