代码之家  ›  专栏  ›  技术社区  ›  Nameless King

用二分法求数的平方根问题

  •  2
  • Nameless King  · 技术社区  · 7 年前
    #include<iostream>
    #include<cmath>
    using namespace std;
    double bisection(double errorVal, double userNum){
        double upper=userNum, lower=0;
        double mid=(lower+upper)/2.0;;
        while(mid*mid!=userNum){
            double mid=(lower+upper)/2.0;
            if(mid*mid>userNum){
                upper=mid;
            } else {
                lower=mid;
            }
        }
        return mid;
    }
    
    int main(){
        double errorVal=0, userNum=0;
        std::cout<<"Please enter a number (larger than 0) to calculate its square root, and the desired margin of error."<<std::endl;
        std::cin>>userNum>>errorVal;
        bisection(errorVal,userNum);
        std::cout<<"The calculated result is "<<bisection(errorVal,userNum)<<". The error is "<<abs(bisection(errorVal,userNum)-sqrt(userNum))<<"."<<std::endl;
    }
    

    我也想知道如何正确实施 errorVal ,以指定允许的误差幅度。谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Stefan    7 年前

    误差值用于修复执行浮点运算时出现的任何舍入误差。

    以下陈述很少是正确的,因此您的循环可能会持续很长时间。

    while(mid*mid==userNum)
    

    计算后比较两个浮点的常用方法是

    fabs(x1-x2) < e //where, fabs retrieves the absolute value, 
                    //x1,2 are the numbers to compare 
                    //and e is the epsilon chosen. 
    

    因此,固定误差值(通常称为epsilon)也会固定循环。

    double bisection(double errorVal, double userNum){
        double upper=userNum, lower=0;
        double mid=(lower+upper)/2.0;
    
         //error val added
         //** fabs(mid*mid - userNum) < errorVal is true if the numers are "equal"
         //** and you want to run the loop as long as the are NOT "equal" 
         while(!(fabs(mid*mid - userNum) < errorVal)){
    
            mid=(lower+upper)/2.0;
            if(mid*mid>userNum){
               upper=mid;
            } else {
                lower=mid;
            }
        }
        return mid;
    }
    

    请参阅: http://www.cplusplus.com/reference/cmath/fabs/

    https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/