C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The Math.round method changes 10.1 to 10, and 10.5 to 11. So it rounds down and up depending on the number's fractional value.
Java program that uses Math.round on doubles
import java.lang.Math;
public class Program {
public static void main(String[] args) {
double[] values = { 10.1, 10.5, 10.9, 10 };
// Round some double values.
for (double v : values) {
// This Math.round receives a double and returns along.
long result = Math.round(v);
System.out.println(v + ": " + result);
}
}
}
Output
10.1: 10
10.5: 11
10.9: 11
10.0: 10
Java program that uses Math.round on floats
import java.lang.Math;
public class Program {
public static void main(String[] args) {
float value1 = (float) 10.1;
float value2 = (float) 10.5;
// Use Math.round on floats.
int result1 = Math.round(value1);
int result2 = Math.round(value2);
// Display results.
System.out.println(value1 + ": " + result1);
System.out.println(value2 + ": " + result2);
}
}
Output
10.1: 10
10.5: 11
Version 1: This version of the code repeatedly calls Math.round to get a round number from a double.
Version 2: Here we store the result of Math.round in a HashMap, and then repeatedly call get() to access the cached result.
Result: It appears that Math.round is faster than a HashMap lookup. This defeats the optimization.
Tip: Lookup tables often improve program performance, but only if the lookup time is less than the original computation time.
Java program that benchmarks Math.round, HashMap
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Place a Double key in this HashMap.
HashMap<Double, Long> roundCache = new HashMap<>();
double value = 1000.5;
roundCache.put(value, Math.round(value));
long t1 = System.currentTimeMillis();
// Version 1: use round.
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
// Use Math.round method directly.
long result = Math.round(value);
if (result != 1001) {
return;
}
}
}
long t2 = System.currentTimeMillis();
// Version 2: use get() to look up a value.
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
// Use get.
long result = roundCache.get(value);
if (result != 1001) {
return;
}
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
7 ms: Math.round calls
358 ms: HashMap get calls