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?
#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.