Java Math.sqrt Method: java.lang.Math.sqrt

This Java example uses the Math.sqrt method to compute square roots. Sqrt can be called as java.lang.Math.sqrt.
Math.sqrt. In mathematics, a square root maps the area of a square to the length of its side. In Java we use the Math class to compute square roots.
With this method, we receive a double. For programs that call Math.sqrt many times, a lookup table cache can be used. This approach (memoization) helps many programs.
Square root. Consider this program. It does not import java.lang.Math at its top. Instead we directly access Math.sqrt using its composite name. It shows the output of sqrt.

Result: The square root of 4 is 2. We see 2.0 because Math.sqrt returns a double.

Tip: For cases when we do not need fractional values, we can cast the result of Math.sqrt to an int.

Casts
Java program that uses Math.sqrt public class Program { public static void main(String[] args) { // ... Test the sqrt method. double value = java.lang.Math.sqrt(4); double value2 = java.lang.Math.sqrt(9); System.out.println(value); System.out.println(value2); } } Output 2.0 3.0
Lookup table. Memoization is a powerful programming technique. In it, we avoid computing a data we previously computed. We store values in a structure like an array.

And: We then use the cached data directly, avoiding an expensive call like Math.sqrt.

Here: We use a double array cache of 100 Math.sqrt values. We access those values many times.

Arrays

Result: Accessing array elements is more than ten times faster than calling Math.sqrt each time.

Java program that uses Math.sqrt lookup table public class Program { public static void main(String[] args) { // A lookup table for square roots. double[] cache = new double; long t1 = System.currentTimeMillis(); // Version 1: use Math.sqrt each time. for (int i = 0; i < 1000000; i++) { for (int x = 1; x < 100; x++) { double result = Math.sqrt(x); if (result == 0) { return; } } } long t2 = System.currentTimeMillis(); // Version 2: use lookup table after first time. for (int i = 0; i < 1000000; i++) { for (int x = 1; x < 100; x++) { double result; if (cache[x] != 0) { result = cache[x]; } else { result = Math.sqrt(x); cache[x] = result; } if (result == 0) { return; } } } long t3 = System.currentTimeMillis(); // ... Benchmark times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 594 ms Math.sqrt 47 ms Cache lookup, Math.sqrt if not found
Some notes, memoization. The exact usage of Math.sqrt is good to know. But optimization techniques like memoization are more general purpose. They can help us develop many programs.
Square root review. As a developer I rarely need to call Math.sqrt. But this makes the Math class even more important. A custom implementation would be less reliable and useful.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls