如果输入的数字超过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;
}发布于 2015-01-15 07:11:17
我相信你应该使用相对错误来终止,而不是绝对错误。
while (abs((guess*guess-x) / guess) > 0.00001)否则,计算很长值的平方根需要很长的时间(不是无限循环)。
错误
干杯!
此外,正如注释中所指出的那样,编辑:值得检查是否已经猜到了guess,以避免某些特定角落情况下的无限循环。
发布于 2015-01-15 07:28:34
我建议等到你得到一个稳定的答案,而不是摆弄epsilon的值:
double squareroot(double x)
{
if (x < 1) return 1.0 / squareroot(x); // MSalter's general solution
double xhi = x;
double xlo = 0;
double guess = x/2;
while (guess * guess != x)
{
if (guess * guess > x)
xhi = guess;
else
xlo = guess;
double new_guess = (xhi + xlo) / 2;
if (new_guess == guess)
break; // not getting closer
guess = new_guess;
}
return guess;
}发布于 2015-01-15 07:21:50
--这不是对你问题的直接回答,而是另一种解决办法。
您可以使用牛顿寻根法
assert(x >= 0);
if (x == 0)
return 0;
double guess = x;
for (int i=0; i<NUM_OF_ITERATIONS; i++)
guess -= (guess*guess-x)/(2*guess);
return guess;24次迭代可以得到足够好的近似,但也可以检查绝对值的差别。
https://stackoverflow.com/questions/27958136
复制相似问题