使用二分法查找数的平方根时出现问题


#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/

最新更新