Ant*_*ndo 1 java math comparison
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
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用巴比伦算法实现一个简单的 squareRoot 方法。我的问题是对于小于 0.01 的数字,结果非常不准确。
我希望循环运行,直到两个数字(过去猜测和猜测)彼此相差 1% 以内,但我无法计算出正确的数学方法。
我想出了:
((pastGuess / guess) >= 1.01)
Run Code Online (Sandbox Code Playgroud)
我也试过:
((pastGuess / guess) >= 1.01 || (guess / pastGuess ) >= 1.01)
Run Code Online (Sandbox Code Playgroud)
这工作得更好,但有没有更有效的方法呢?
double ratio = pastGuess / guess;
(ratio >= 1.01 || ratio <= 0.99)
Run Code Online (Sandbox Code Playgroud)
请注意,我用于0.99可读性。上述验证对称的正确值将是一个常数等于(100/101) = 0.99009900...