Search code examples
javamathseriessquare-root

Determine square root of a double with series


The problem:

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.

My solution is similar, but without using this formula:

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;`
}

Solution

  • This algorithm is known as the Babylonian method. It converges for any positive initial value, so your code is correct.

    However, you should return as soon as the absolute difference between consecutive values becomes less than a small value (say, 1e-10) to make sure the code ends. Otherwise there is a risk of infinite loop.