如何在Boost C ++中对具有多个参数的函数使用二等分方法

问题描述

我在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);
}

如您所见,my_fn接受两个参数xy。但是我想找到给定y = 1的此函数解决方案。

请帮助您使用bisection方法找到解决方案?

解决方法

#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是模板。第一个参数是可调用的(用于最小化的函数),然后是初始括号(最小值和最大值),最后一个参数是可调用的,用于评估停止条件。

或者您可以编写一个函数:

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

并将其最小化。

PS:该函数不会返回 解决方案,而是返回使停止条件成立的最终间隔。真正的解决方案是在此间隔内的某个地方。

,

您可以使用 lambda (很有可能编译器会内联所有内容),如下所示:

#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,boost::math::tools::eps_tolerance<double>());

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

  return 0;
}

打印:

Result 1.41421,1.41421

您可以在此处{@ 3}了解有关lambda和lambda捕获的信息。