Square Root Algorithm with Newton Raphson.

Precise Square Root using Newton Raphson Method.

We want to calculate square root n.

n^(1/2) = x          Lets say x is the square root of n.
n = x^2                squared both side.
x^2 – n = 0          moved n to the other side.
f(x) = x^2 – n.
Newton raphson iterative method formula.

Lets find derivative of our equation.
f ‘(x) = 2x

Simplify the Equation:

Xn+1 = Xn – (Xn^2 – n) / 2Xn

Xn+1 = (2Xn^2 – Xn^2 + n) / 2Xn

Xn+1 = (Xn^2 + n) / 2Xn

Xn+1 = (Xn + n/Xn)/2

take guess value of Xn lets say 1,
and keep iterating to calculate Xn+1
and stop when (Xn+1 – Xn) <= required precision.

Pseudo Code:

float square_root(int n)
{
    float x = 1; //guess value.
    while (true)
    {
        float lastX = x;
        x = (x + n/x) /  2;
        if (abs(x - lastX) <= 0.00001)
        {
            break;
        }
    }
    return x;
}

public class Solution {
    public static double squareRoot(int n) {
        final double precison = 0.0000001;
        final double guess = 1;
        double x = guess;
        double lastX;
        do {
            System.out.println(x);
            lastX = x;
            x = (x + n/x)/2;
        } while ((Math.abs(x - lastX)) > precison);
        return x;
    }

    public static void main(string[] args) {
        System.out.println(squareRoot(2));
    }
}

Output:

1.0
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
1.414213562373095

Leave a comment