二分法求方程的解

/*求下面方程的一个根:f(x)=x^3-5x^2+10x-80=0
若求出一个根为a,则要求f(a)的绝对值小于10^-6
解法,求导缩小为0,100,用二分的方法在[0,100]内求解*/


#include <iostream>
#include <cmath>
#include <cstdio>


using namespace std;
double EPS = 1e-6;
double f(double x)
{
    return x*x*x-5*x*x+10*x-80;//double类型不可以用^
}
int main()
{
    double root,x1 = 0,x2 = 100, y;
    root = x1+(x2-x1)/2;
    int triedtimes = 1;
    y = f(root);//求出对应的x对的返回值,无限接近于0。
    while(fabs(y)>EPS)
    {
        if(y>0) x2 = root;
        else x1 = root;
        root = x1+(x2-x1)/2;
        y = f(root);
        triedtimes++;
    }
    printf("%.8f\n",root);
    printf("%d",triedtimes);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/huzi99/article/details/79416535