Java

Math

Cast

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);
}
}2.0
3.0

Array

public class Program {
public static void main(String[] args) {
*// A lookup table for square roots.*
double[] cache = new double[100];
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);
}
}594 ms Math.sqrt
47 ms Cache lookup, Math.sqrt if not found

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

No updates found for this page.