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

Problems finding a number's square root with bisection method

#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,以指定允许的误差范围。谢谢

错误值用于修复在进行浮点运算时发生的任何舍入不准确。

下面的说法很少是真的,因此你的循环很可能会持续很长时间。

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/