(二分查找)方程求根

求方程的一个根:f(x)=x^3-5x^2+10x-80=0,要求|f(a)|<=10^-6。

题解:
求导后可知该方程单增,且f(0)<0,f(100)>0。

 #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cmath>
using namespace std;
double EPS = 1e-6;
int f(double x)
{
 return x * x * x - 5 * x * x + 10 * x - 80;
}
int main()
{
 double begin = 0, end = 100;
 double x = begin + (end - begin) / 2;
 double y = f(x);
 while (fabs(y) > EPS) {
  if (y > 0) {
   end = x;
  }
  else {
   begin = x;
  }
  x = begin + (end - begin) / 2;
  y = f(x);
 }
 printf("%.8f\n", x);
 return 0;
}

posted @ 2020-02-23 17:31  BlueValentines  阅读(311)  评论(0)    收藏  举报