How to use the bisection method in boost C++ for a function with multiple arguments

Viewed 277

I have below function in C++

#include <cmath>
#include <utility>
#include <iostream>
#include <boost/math/tools/roots.hpp>

double my_fn(double x, double y)
{
    return x*x - y - 1;
};

int main() {
    double min_x = 0.0;  // min value of domain of x
    double max_x = 10.0; // max value of domain of x
    double y = 1;

    // how to use boost's bisection to find solution of my_fn for y = 1
    return (0);
}

As you see my_fn takes 2 arguments x and y. However I want to find solution of this function given y = 1.

Can you please help to find solution using bisection method?

2 Answers
#include <cmath>
#include <utility>
#include <iostream>
#include <boost/math/tools/roots.hpp>

double my_fn(double x, double y)
{
    return x*x - y - 1;
};

int main() {
    double min_x = 0.0;  // min value of domain of x
    double max_x = 10.0; // max value of domain of x
    double y = 1;
    auto x = boost::math::tools::bisect(
            [y](double x){ return my_fn(x,y); },
            min_x,
            max_x,
            [](double x,double y){return abs(x-y) < 0.01;}
    );
    std::cout << "The minimum is between x=" << x.first << " and x=" << x.second;
    // how to use boost's bisection to find solution of my_fn for y = 1
    return (0);
}

bisect is a template. The first parameter is a callable (the function to minimize), then the initial bracket (min and max) and the last parameter is a callable that evaluates the stop condition.

Alternatively you can write a function:

double my_fn_y1(double x) {
    return my_fn(x,1);
}

and minimize that.

PS: The function does not return the solution, but rather the final interval which makes the stop condition true. The real solution is somewhere in that interval.

You can use a lambda (with good chance that the compiler inlines everything), like this:

#include <boost/math/tools/roots.hpp>
#include <iostream>
   
double my_fn(double x, double y) { return x * x - y - 1; };

int main()
{
  double min_x = 0.0;   // min value of domain of x
  double max_x = 10.0;  // max value of domain of x
  double y = 1;

  std::pair<double, double> result =
      boost::math::tools::bisect([y](double x) { return my_fn(x, y); },
                                 min_x,
                                 max_x,
                                 boost::math::tools::eps_tolerance<double>());

  std::cout << "Result " << result.first << ", " << result.second;

  return 0;
}

which prints:

Result 1.41421, 1.41421

You can read about lambda and lambda capture here: cpp.reference lambda section.

Related