Java Calculate Square Root Without Using Library Method

If we want to calculate square root, we can use Math.sqrt() method. It is simple. Now do you know how to write such a method by yourself?

Here is the equation you need.

java square root

The first sqrt number should be the input number / 2.

Using the equation, we can come up with a Java Square Root method by ourselves.

public static double sqrt(int number) {
	double t;
 
	double squareRoot = number / 2;
 
	do {
		t = squareRoot;
		squareRoot = (t + (number / t)) / 2;
	} while ((t - squareRoot) != 0);
 
	return squareRoot;
}

4 thoughts on “Java Calculate Square Root Without Using Library Method”

Leave a Comment