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
- Start with an initial guess (we use half of the input number).
- Improve the guess using the Newton formula.
- Repeat until the difference between two successive guesses is very small.
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)
- Initial Guess = 25 / 2 = 12.5
- Next Guess = (12.5 + 25 / 12.5) / 2 = 7.25
- Next Guess = (7.25 + 25 / 7.25) / 2 = 5.349
- Next Guess = (5.349 + 25 / 5.349) / 2 = 5.011
- Next Guess = (5.011 + 25 / 5.011) / 2 = 5.0000 (accurate)
Within just a few iterations, we reach the exact square root!
Practice Challenges
- Modify the program so the user can enter the precision value (e.g., 0.01, 0.0001).
- Rewrite the program to calculate cube root using the Newton–Raphson method.
- 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.