【发布时间】:2015-01-15 06:53:14
【问题描述】:
如果输入的数字超过 12 位,我无法弄清楚为什么该算法会进入无限循环。谁能明白为什么它永远不会结束?谢谢。我刚刚更新了算法以使用 fabs() 函数并且仍然得到一个无限循环。
double squareroot(double x)
{ /* computes the square root of x */
/* make sure x is not negative .. no math crimes allowed! */
assert( x >= 0 );
if (x==0) return 0;
/* the sqrt must be between xhi and xlo */
double xhi = x;
double xlo = 0;
double guess = x/2;
/* We stop when guess*guess-x is very small */
while (abs(guess*guess-x) > 0.00001 )
{
if (guess*guess > x){
xhi = guess;
}
else {
xlo = guess;
}
guess = (xhi + xlo)/2;
}
return guess;
}
【问题讨论】:
-
abs是一个整数函数。你的意思是fabs? -
guess*guess的 12 位数字?那会很大.. -
您对终止标准的固定 epsilon 可能也应该相对于输入值表示。否则,您对 16.0e-8 的计算甚至不会进入第一次迭代。
-
标签: c++ algorithm oop square-root