浮点数开根号 二分法+牛顿法

double sqrt_bin(double n){
    if(n < 1){
        n = 1;
    }
    double left = 0;
    double right = n;
    double mid = n / 2;
    while(abs(mid * mid - n) > 0.000001){
        if(mid*mid < n){
            left = mid;
        }
        else{
            right = mid;
        }
        mid = (left + right) / 2;
    }
    return mid;
}


double sqrt_newton(double n){
    if(n < 1){
        n = 1;
    }
    double x0 = n;
    double x1 = x0;
    while(x1 * x1 - n > 0.0000001){
        x1 = 0.5 * (x0 + n / x0);
        x0 = x1;
    }
    return x0;
}



// 更新:开三次根号其实也差不多 注意一些细节就行了
double sqrt3_nt(double n){
    if ( n > -1 && n < 1){
        n = 1;
    }
    double left = n;
    double right = n;
    while(abs(left * left * left - n) > 0.0001){
        cout << left << " "<< right << endl;
        left = (1.0/3) * (n / (right * right) + 2 * right);
        right = left;
    }
    return left;
}

posted @ 2018-09-03 22:42  一条图图犬  阅读(701)  评论(0编辑  收藏  举报