public static double squareRoot(double num) throws IllegalArgumentException
{
if (num < 0.0)
throw new IllegalArgumentException("Number cannot be negative.");
double guess = num / 2.0, pastGuess;
guess = 0.5 * (guess + (num / guess));
do {
pastGuess = guess;
guess = 0.5 * (guess + (num / guess));
} while ((pastGuess / guess) >= 1.01);// run until both numbers are within 1% of each other
return guess; // return square root of num
}
我试图使用巴比伦算法实现一个简单的 squareRoot 方法。我的问题是,对于小于 0.01 的数字,结果非常不准确。
我希望循环运行,直到两个数字(过去的猜测和猜测)都在 1% 以内(如果彼此),但我无法弄清楚它的正确数学。
我想出了:
((pastGuess / guess) >= 1.01)
我也试过:
((pastGuess / guess) >= 1.01 || (guess / pastGuess ) >= 1.01)
这工作得更好,但有没有更有效的方法呢?