Inspired by Weiqi Gao's Friday Java Quiz this week, I came up with a few more curiosities of Java double. What do each of the calls to larger() print? Hint: this puzzle has nothing to do with type conversion loss of precision, it is only about the specified behavior of doubles.
public class Foo {
public static void main(String[] args) {
larger(0.0d, Double.MIN_VALUE);
larger(1.0d, Double.MIN_VALUE*Double.MAX_VALUE);
larger(1.0d, Double.MIN_VALUE*Double.MAX_VALUE*Double.MAX_VALUE);
larger(1.0d/Double.MIN_VALUE, 1.0d/(1.0d/Double.MAX_VALUE));
larger(1.0d/Double.MIN_VALUE, 1.0d/0.0d);
larger(1.0d, Double.MIN_VALUE/Double.MIN_VALUE);
}
public static void larger(Double a, Double b){
System.out.print(a + " or " + b + " ? ");
if (a < b){
System.out.println(b);
} else if (a > b){
System.out.println(a);
} else {
System.out.println("equal");
}
}
}
Highlight the hidden text below for the answers:
0.0 or 4.9E-324 ? 4.9E-324
1.0 or 8.881784197001251E-16 ? 1.0
1.0 or 1.5966722476277755E293 ? 1.5966722476277755E293
Infinity or Infinity ? equal
Infinity or Infinity ? equal
1.0 or 1.0 ? equal
Post a Comment