In the world of mathematics and programming, the square root is a fundamental operation used in various applications. Whether you’re a Java developer or someone interested in math, understanding how to calculate the square root of a number in Java is a valuable skill. Java, as a versatile programming language, offers built-in functions for this purpose, but it’s also essential to grasp the underlying algorithms and implement custom methods for specific scenarios.
What is Square and Square root?
Square:
In mathematics, “square” refers to the result of multiplying a number by itself. For any real number “a,” the square of “a” is denoted as “a^2,” which means “a” multiplied by “a.” The square of a number is always a non-negative value because multiplying a negative number by itself results in a positive value.
For example:
– The square of 2 is 2^2 = 2 * 2 = 4
– The square of -3 is (-3)^2 = -3 * -3 = 9
Square Root:
The square root of a non-negative number “a” is a value “x” such that when “x” is multiplied by itself, it gives “a.” Moreover, square root is denoted by the symbol “√” or as “a^(1/2).” The square root is the opposite operation of squaring, and it helps find the original number from its square.
For example:
– The square root of 25 is √25 = 5, as 5 * 5 = 25.
– The square root of 9 is √9 = 3, as 3 * 3 = 9.
It’s important to note that for negative numbers, the square root is not a real number, but it is a complex number. For example, the square root of -9 is √(-9) = 3i, where “i” is the imaginary unit (√(-1)).
Real and Imaginary Square Roots
Square roots can be categorized into two types: real and imaginary. Real square roots are positive or zero values that result from the square of non-negative numbers. For negative numbers, the square root is considered imaginary because it involves the use of complex numbers. However, in Java, we will mainly focus on calculating the square roots of non-negative real numbers.
Properties of Square Roots
Square roots possess certain properties that make them useful in various mathematical operations and scientific calculations. For instance, the square root of a product of two numbers is equal to the product of their individual square roots, and the square root of a quotient is the quotient of their individual square roots. These properties are essential in solving complex equations and problems involving square roots.
Java Program to Find the Square Root of Number Using Newton-Raphson
import java.util.Scanner; public class FindSqrRootEx { public static void main(String[] args) { System.out.print("Enter a number: "); //creating object of the Scanner class Scanner sc = new Scanner(System.in); //reading a number form the user int number = sc.nextInt(); //calling the method and prints the result System.out.println("The square root of "+ number+ " is: "+squareRoot(number)); } //user-defined method that contains the logic to find the square root public static double squareRoot(int num) { //temporary variable double t; double sqrtroot=num/2; do { t=sqrtroot; sqrtroot=(t+(num/t))/2; } while((t-sqrtroot)!= 0); return sqrtroot; } }
Explanation of the code:
This code calculates the square root of a number in Java using the Newton-Raphson method. Let’s delve into the inner workings of the code.
1. The code prompts the user to enter a number using the Scanner class and stores it in the variable “number.”
2. The code then calls the “squareRoot” method, passing the entered number as an argument.
3. In the “squareRoot” method, a temporary variable “t” is declared, and the initial guess for the square root is set to “number/2” in the variable “sqrtroot.”
4. The code enters a do-while loop, which repeatedly refines the square root approximation using the Newton-Raphson formula: “sqrtroot = (t + (number/t)) / 2.”
5. The loop continues as long as the difference between “t” and “sqrtroot” is not equal to 0, indicating that the approximation is still being refined.
6. Once the loop exits, the final value of “sqrtroot” holds the square root approximation.
7. The method returns the calculated square root, which is then printed as the result.
The Newton-Raphson method is an iterative algorithm that efficiently calculates square roots and provides a close approximation to the actual square root of the number. It iteratively enhances the initial guess until achieving the desired precision, making it an effective approach for finding square roots in Java.
Output:
Enter a number: 81
The square root of 81 is: 9.0
Java Program to Find the Square Root of a Number with Precision (Binary Search Algorithm)
import java.util.Scanner; public class FindSqrRootEx { public static void main(String[] args) { double num = 0, sqrt=0; //object of the Scanner class Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); //reading a double value from the user num = sc.nextDouble(); //method calling sqrt = squareRoot(num); //prints the result System.out.println("The square root of "+num+ " is "+sqrt); } //user-defined method to find the square root of a number private static double squareRoot(double num) { //iterator variable int i = 1; while(true) { //for perfect square numbers if(i*i == num) return i; //for not perfect square numbers else if(i*i > num) //returns the value calculated by the method decimalSqrt() return decimalSqrt(num,i-1,i); //increments the variable i by 1 i++; } } // recursive method to find the square root of a number up to 7 decimal places private static double decimalSqrt(double num, double i, double j) { //calculates the middle of i and j double midvalue = (i+j)/2; //finds the square of the midvalue double square = midvalue * midvalue; //compares the midvalue with square up to n decimal places if(square==num||Math.abs(square-num)<0.0000001) return midvalue; //if the square root belongs to second half else if(square>num) return decimalSqrt(num, i, midvalue); //if the square root belongs to first half else return decimalSqrt(num, midvalue, j); } }
Explanation of the code: “FindSqrRootEx”
The purpose of this program is to calculate the square root of a given number with high precision. It uses both iterative and recursive methods to achieve this task.
1. The program starts with importing the “java.util.Scanner” package to read input from the user.
2. The main method is the entry point of the program. It first declares and initializes variables “num” and “sqrt” to store the input number and the calculated square root, respectively.
3. The program uses the “Scanner” class to read a double value from the user. The prompt prompts the user to enter a number, and the variable “num” stores the entered value.
4. The “squareRoot” method is a user-defined method that takes the input number “num” and returns its square root. It uses a while loop to find the square root iteratively.
5. The method uses an iterative approach to find the square root. It starts with an iterator variable “i” initialized to 1. The while loop keeps running until it finds a perfect square or an approximate square.
6. If the value of “i * i” is equal to the input number “num,” it means that “num” is a perfect square, and the method returns the value of “i” as the square root.
7. If “i * i” is greater than “num,” it means that “num” is not a perfect square. In this case, the method calls the “decimalSqrt” method, which uses a recursive approach to find the square root with high precision.
8. The “decimalSqrt” method is a recursive method that calculates the square root of a number up to seven decimal places. It takes three parameters – “num” (the input number), “i” (the lower limit for the search), and “j” (the upper limit for the search).
9. The method calculates the middle value (“midvalue”) between “i” and “j”.
10. It then calculates the square of “midvalue” and compares it with “num”.
11. If “midvalue” squared equals “num,” or if the absolute difference between the square of “midvalue” and “num” is less than 0.0000001 (ensuring seven decimal places of precision), the method concludes that it has found the square root. Subsequently, it returns “midvalue” as the square root.
12. If the square of “midvalue” is greater than “num,” it means the square root belongs to the first half. The method calls itself recursively, updating the upper limit (“j”) to “midvalue.”
13. If the square of “midvalue” is less than “num,” it means the square root belongs to the second half. The method calls itself recursively, updating the lower limit (“i”) to “midvalue.”
14. The main method then prints the calculated square root of the input number with the message “The square root of (num) is (sqrt).”
This Java program efficiently finds the square root of a number in Java with high precision using iterative and recursive approaches. It’s important to note that the recursive method (“decimalSqrt”) is called only when the input number is not a perfect square, ensuring the program’s efficiency for both perfect square and non-perfect square inputs.
Output:
Enter a number: 25
The square root of 25.0 is 5.0
In conclusion, understanding how to calculate the square root of a number in Java is a valuable skill for any programmer. Whether using built-in functions or implementing custom methods, Java offers versatile approaches to find square roots efficiently. By grasping the underlying algorithms, developers can confidently handle square root calculations and excel in their programming journey.
We hope that our blog post on “Square Root of a Number in Java” will answer any queries you may have about Java. As you continue to develop your coding skills, visit the Newtum’s website to learn more about our online coding courses in Java, Python, PHP, and other topics. With practice and dedication, you can master Java development and learn new programming concepts. Happy coding!