二分法递归版本(c++)

利用二分法求解在区间[0,π/2]上的根

#include<iostream>

#include <cmath>

using namespace std;

double dichotomy(double begin, double end);

int main()

{

      const double pi = 3.14;      //定义π的值

      double begin = 0;      //定义域区间的起始值

      double end = pi / 2;      //定义域区间的结束值                                

      if (dichotomy(begin, end) == 1000000000)

            cout << "无解" << endl;

      else

            cout << "所求解的值为" << dichotomy(begin,end) << endl;

      return 0;

}

double dichotomy(double begin, double end)

{

      if (begin == 0)     

            begin += 0.01;      //由于本例中,分母不能为0,故对起始值为0的情况,对起始值加0.01

      double begin_value = 1 / begin - tan(begin);      //区间函数起始值,

      double end_value = 1 / end - tan(end);      //区间函数结束值

      double middle = (begin + end) / 2;      //定义域的中间值

      double result;      //定义域中间值的函数值

      if ((begin_value > 0 && end_value > 0) || (begin_value < 0 && end_value < 0))

            return 1000000000;

      

      if (fabs(begin_value) < 0.000001)

            return begin;

      

      if (fabs(end_value) < 0.000001)

            return end;

      

      result = 1 / middle - tan(middle);

      if (fabs(result) < 0.000001)

            return middle;

      else

      {

            if ((begin_value > 0 && result > 0) || (begin_value < 0 && result < 0))

                  begin = middle;

            else

                  end = middle;

            return dichotomy(begin, end);

      }

}

运行结果

二分法递归版本(c++)

posted @ 2015-11-27 18:37  硫酸亚铜  阅读(444)  评论(0编辑  收藏  举报