# How to Make a Square Root Function in Java

Written by joe wandy
• Share
• Tweet
• Share
• Pin
• Email

To find the square root of a number, you need to find the inverse operation of multiplying a number by itself. While the Java programming language provides a built-in "Math.sqrt()" function to calculate the square root of any number, it accepts only a floating-point double value data type. However, you may find yourself needing to find the square root of a number in a different data type. For this purpose, you can build a custom function to compute the square root value manually.

Skill level:
Moderate

## Instructions

1. 1

Define a method to calculate the square root. You should give the method a descriptive name that reflects its function. Ensure that all the necessary elements of a method are present, namely its return type, name, enclosing parentheses for method arguments and the body declaration in braces. For example, an appropriate method to get the square root of a number is:

public BigDecimal get (BigDecimal n) { }

2. 2

Complete the body code of the method by writing an algorithm to calculate the approximation of the square root of a number. You may use the Newton's Iteration method to form the mathematical basis of your calculation. In this method, you can calculate the square root of a number by repeatedly solving the recurrent equation xk + 1 = 1/2(xk + n/xk) until the approximation value comes close to the actual square root value. For example, the following is a code segment in Java that performs this calculation:

``````iterations = 0;

boolean more = true;

while (more) {

last Guess = guess;

guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);

guess = guess.divide (TWO, scale, BigDecimal.ROUND_HALF_UP);

trace ("Next guess " + guess.toString ());

error = n.subtract (guess.multiply (guess));

if (++iterations &gt;= max Iterations) {

more = false;

}

else if (lastGuess.equals (guess)) {

more = error.abs ().compare To (ONE) &gt;= 0;

}

}

return guess;
``````
3. 3

Define other supporting methods to the main square-root finding method, whenever necessary. You can find yourself needing to define methods to find the initial approximation value, calculate error and set number of iterations. For example, the following code finds the initial approximation value to be used in the main calculation:

private static BigDecimal getInitialApproximation (BigDecimal n) {

``````BigInteger integer Part = n.toBigInteger ();

int length = integerPart.toString ().length ();

if ((length % 2) == 0) {

length--;

}

length /= 2;

BigDecimal guess = ONE.movePointRight (length);

return guess;
``````

}

4. 4

Test your square root method by calling it and printing the result to the screen. For example:

System.out.println ("Computing the square root of");

sqrt = app.get (n);

### Don't Miss

#### Resources

• All types
• Articles
• Slideshows
• Videos
##### Sort:
• Most relevant
• Most popular
• Most recent