【数值计算方法】二分法求根的C++简单实现

原文链接: http://www.cnblogs.com/robotpaul/p/10625966.html
给定精确度ξ,用二分法求函数f(x)零点近似值的步骤如下:
1 确定区间[a,b],验证f(a)·f(b)<0,给定精确度ξ.
2 求区间(a,b)的中点c.
3 计算f(c).
(1) 若f(c)=0,则c就是函数的零点;
(2) 若f(a)·f(c)<0,则令b=c;
(3) 若f(c)·f(b)<0,则令a=c.
(4) 判断是否达到精确度ξ:即若|a-b|<ξ,则得到零点近似值a(或b),否则重复2-4
double fun(double a, double b,double ep)//二分法,[a,b]区间进行迭代递归,ep是精度
{
    int k = 0;
    while (abs(a - b) > 2 * ep)
    {
        double x0 = (a + b) * 0.5;
        double fx0 = fx(x0);
        double fa = fx(a);
        double fb = fx(b);
        if (fa * fx0 < 0)
        {
            b = x0;
        }
        else if (fa * x0 == 0)
        {
            break;
        }
        else
        {
            a = x0;
        }
        k++;
        printResult(a, b, k);
    }
    return (a + b )*0.5;
}
double fx(double x)//函数式只需要对返回值进行修改即可
{
    return exp(x) - x * x + 3.0 * x - 2.0;
}
void printResult(double ax, double bx,int k)
{
    cout<"\t" << ax << "\t" << bx << "\t" << (ax+bx)*0.5 << "\t";
    if (fx((ax + bx) * 0.5) > 0)
    {
        cout << "+" << endl;
    }
    else
    {
        cout << "-" << endl;
    }
}

 

转载于:https://www.cnblogs.com/robotpaul/p/10625966.html

你可能感兴趣的:(【数值计算方法】二分法求根的C++简单实现)