我想制作一个程序,使用巴比伦算法计算正数 n 的平方根,如下所示:
现在这是我的代码。
double n = input.nextDouble();
double guess = n / 2;
while ()
{
double r = n / guess;
guess = (guess + r) / 2;
System.out.println(guess);
}
当猜测在前一次猜测的1%范围内时,如何让循环停止迭代?我没有得到“猜测在前一次猜测的1%以内”的部分。
答案 0 :(得分:2)
这应该可以解决问题:
double n = input.nextDouble();
double guess = n / 2;
double pctDiff = Double.MAX_VALUE;
double lastGuess = guess;
while (Math.abs(pctDiff) >= 0.01)
{
double r = n / guess;
guess = (guess + r) / 2;
pctDiff = ((guess-lastGuess)/lastGuess); // normally, multiply by 100, but don't need to necessarily...
lastGuess = guess;
System.out.println(guess);
}
答案 1 :(得分:0)
将先前和当前猜测存储在单独的变量中。然后只需使用if语句检查currentGuess
与previousGuess
之间的距离。
答案 2 :(得分:0)
本书Algorithms中列出的算法用于平方根和解释 添加是
public static double sqrt(double c)
{
if (c < 0) return Double.NaN;// less than zero are complex numbers
double err = 1e-15; // (1 power -15)decreasing this will cause more accuracy
// and more iterations to converge(quadratic
// convergence) toward the actual value
double t = c; // initial positive value
while (Math.abs(t - c/t) > err * t)
t = (c/t + t) / 2.0;
return t;
}