用级数确定双精度数的平方根

Determine square root of a double with series

问题:

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),您就应该 return 以确保代码结束。否则有死循环的风险。