How to use boost bisection?

后端 未结 2 1143
别跟我提以往
别跟我提以往 2020-12-15 12:56

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.

<
相关标签:
2条回答
  • 2020-12-15 13:22

    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());
    
    0 讨论(0)
  • 2020-12-15 13:40

    Note that bisect also supports 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;}
    );
    
    0 讨论(0)
提交回复
热议问题