我遇到了必须计算给定参数的根平方的Java代码的麻烦。然而,经过一些研究后,我发现了一个我不知道如何正确实现的代码。
// read in the command-line argument
double c = Double.parseDouble(args[0]);
double epsilon = 1.0e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is achieved
while (Math.abs(t - c/t) > epsilon *t) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
我不完全理解的第一件事就是为什么他们在8号线上除以2。
t = (c/t + t) / 2.0;
我不明白的第二件事是来自while循环的条件,更确切地说:
while(Math.abs(t - c/t) > epsilon*t)
没有必要只有:
while(Math.abs(t - c/t) > epsilon)
t = (c/t + t) / 2.0;
这用于计算两个值c/t
和t
的平均值/平均值。该值存储在变量t
中,用于下一次循环迭代。在System.out.println()
循环中使用while
调用来检查此行之前的t
和c/t
的值以及此行之后的值。