Java Program to Find the Square Root of Any Number Using the Newton–Raphson Method

Learn how to calculate the square root of any number in Java using the Newton–Raphson numerical method. This efficient algorithm provides fast and accurate results without using Math.sqrt().

Java Program to Find the Square Root Using the Newton–Raphson Method

Finding the square root of a number without using Math.sqrt() is a great way to understand numerical methods. One of the fastest and most accurate techniques is the Newton–Raphson method.

This method starts with an initial guess and iteratively improves it using the formula:


xₙ₊₁ = (xₙ + number / xₙ) / 2

With each iteration, the guess becomes more accurate, making this algorithm extremely fast for large values.

How the Newton–Raphson Method Works

Java Program:


import java.util.Scanner;

public class SquareRootNewton {

    public static double squareRoot(double num) {
        if (num < 0) {
            throw new IllegalArgumentException("Square root of a negative number is not real.");
        }

        double guess = num / 2.0;

        // Keep improving until change becomes very small
        while (Math.abs(guess * guess - num) > 0.00001) {
            guess = (guess + num / guess) / 2.0;
        }

        return guess;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        double num = sc.nextDouble();

        double result = squareRoot(num);

        System.out.printf("Square root of %.5f is: %.5f", num, result);
    }
}

Example Output:


Enter a number: 49
Square root of 49.00000 is: 7.00000

Enter a number: 2
Square root of 2.00000 is: 1.41421

This result is extremely close to the real value because the Newton–Raphson method converges very quickly.

Example (Step-by-Step for 25)

Within just a few iterations, we reach the exact square root!

Practice Challenges

  1. Modify the program so the user can enter the precision value (e.g., 0.01, 0.0001).
  2. Rewrite the program to calculate cube root using the Newton–Raphson method.
  3. Handle negative inputs by returning complex square roots instead of throwing an error.

The Newton–Raphson method is one of the fastest ways to compute roots and is widely used in numerical algorithms and engineering computations.