My Computer Science discovers interesting things sometimes. Recently we were doing a little practice with Exceptions and try-catch blocks. One of our projects was to handle division by zero and not crash the program. That sounds like a ordinary project, but as it turns out, it was a more surprising than anyone would have ever thought.
Some Division
To practice, numbers without a decimal are simply integers, otherwise, they are a double.
5 / 2 = 28 / 3 = 210 / 0 = NaN // impossible
You understand integer division just fine right? You can divide a number freely, but there are no decimals, it simply chops off the remainder and any would-be decimals. Division by zero typically throws a Arithmetic Exception.
Something weird happened when those numbers were doubles.
To Infinity and Beyond
Try out this code. You’ll be surprised.
class DoubleDivision {
public static void main(String[] args) {
System.out.println( 5.0 / 0.0 );
}
}
Did you try it? Did you get Infinity? I bet you did. That’s kind of weird.
Why
Java uses Doubles to represent decimals. Binary cannot fully represent a number, it can only represent an approximation and therefore, neither can Java’s double.
Imagine a number incredibly close to zero. If you know calculus, imagine a limit at zero. The variable would be approaching zero to some imaginably tiny distance but never equal exactly. You can imagine that, right? Well, suppose that number is needs so much percision for Java to represent, it gives up and calls it 0.0 because it does not have a good alternative. That’s what is happening here. Any regular number divided by a super close number to zero is basically, infinity. Try it: 5 / (10^-100).
The Double Class documentation attempts to explain some of the toString details. The documentation does not explain this case, but as mentioned above, it might as well be infinity.
So if you divide by zero, and you are using doubles, watch out for Infinity!