问题:
Using the following approximate formula, write a function or method that returns the square root of a real number! Use the sequence x[k + 1] = 1/2 * (x[k] + a / x[k]), which is converges to a square root of 'a' real parameter if x1 = 1.
我的解决方案类似,但没有使用这个公式:
public static double squareRoot(double a) {
double k;
double root = a / 2;
do {
k = root;
root = 0.5*(k+ (a / k));
} while ((k - root) != 0);
return root;`
}
最佳答案
该算法被称为 Babylonian method 。它对于任何正初始值都会收敛,因此您的代码是正确的。
但是,一旦连续值之间的绝对差小于一个小值(例如 1e-10),您就应该立即返回,以确保代码结束。否则有无限循环的风险。
关于java - 使用级数确定 double 的平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137602/