Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Square Root in Java

Square Root in Java

Find Square Root in Java

In Java, you can find the square root of a number using the Math.sqrt() method. This method returns the square root of a given number, or NaN (Not-a-Number) if the number is negative.


1. Using Math.sqrt()

The Math.sqrt(double a) method is used to calculate the square root of a given number a.

Example: Using Math.sqrt()

public class SquareRootExample {    public static void main(String[] args) {        double number = 25.0;                // Calculate the square root using Math.sqrt()        double squareRoot = Math.sqrt(number);                // Print the square root        System.out.println("Square root of " + number + " is " + squareRoot);    }}

Explanation:

  • The Math.sqrt() method computes the square root of the number passed as an argument.

Output:

Square root of 25.0 is 5.0

2. Square Root of Negative Numbers

If you try to compute the square root of a negative number, Math.sqrt() will return NaN (Not-a-Number) because square roots of negative numbers are not defined in the realm of real numbers.

Example: Square Root of Negative Number

public class SquareRootExample {    public static void main(String[] args) {        double number = -25.0;                // Calculate the square root using Math.sqrt()        double squareRoot = Math.sqrt(number);                // Print the result        if (Double.isNaN(squareRoot)) {            System.out.println("Square root of " + number + " is not a real number (NaN)");        } else {            System.out.println("Square root of " + number + " is " + squareRoot);        }    }}

Explanation:

  • When trying to compute the square root of a negative number, Math.sqrt() returns NaN, and we check it using Double.isNaN().

Output:

Square root of -25.0 is not a real number (NaN)

3. Using BigDecimal for Higher Precision

If you need more precision when calculating square roots, you can use BigDecimal to handle very large or very small numbers.

Example: Using BigDecimal

import java.math.BigDecimal;import java.math.MathContext;public class SquareRootBigDecimal {    public static void main(String[] args) {        // Create a BigDecimal number        BigDecimal number = new BigDecimal("25");                // Calculate the square root using BigDecimal's sqrt() method        BigDecimal squareRoot = number.sqrt(new MathContext(10)); // Set precision to 10 digits                // Print the result        System.out.println("Square root of " + number + " is " + squareRoot);    }}

Explanation:

  • BigDecimal provides better precision for decimal calculations.

  • The sqrt() method in BigDecimal requires a MathContext for setting the precision.

Output:

Square root of 25 is 5.0

4. Custom Square Root Calculation (Using Approximation)

If you want to implement a custom method to calculate the square root (for educational purposes or efficiency in specific cases), you can use the Babylonian Method (also known as Heron's Method), which is an iterative algorithm.

Example: Custom Square Root Calculation (Babylonian Method)

public class CustomSquareRoot {    public static void main(String[] args) {        double number = 25.0;                // Calculate the square root using the Babylonian method        double result = sqrt(number);                // Print the result        System.out.println("Square root of " + number + " is approximately " + result);    }    public static double sqrt(double number) {        double guess = number / 2.0;  // Initial guess        double epsilon = 0.0001;  // Desired precision                // Keep updating guess until it's accurate enough        while (Math.abs(guess * guess - number) > epsilon) {            guess = (guess + number / guess) / 2.0;        }                return guess;    }}

Explanation:

  • The Babylonian method starts with an initial guess (half the number) and refines the guess until the square of the guess is sufficiently close to the original number (within a small epsilon).

  • This method is useful when you want to manually calculate the square root without using built-in functions.

Output:

Square root of 25.0 is approximately 5.0

Conclusion

  • Math.sqrt() is the simplest and most efficient way to calculate the square root of a number.

  • Negative Numbers: The square root of negative numbers is not supported by Math.sqrt() and will return NaN.

  • For higher precision, BigDecimal is a good option.

  • Custom methods, like the Babylonian method, can be used for learning or when you need to manually calculate the square root.

Let me know if you need more examples or explanations!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql