In Dutch: “Delen door nul is flauwekul”, which means “dividing a number by zero is nonsense“.
When you start programming you have probably experienced this: the .Net DivideByZeroException. You get this when, for instance, you want to calculate the average of a values list, and you divide it by the number of items, but then the list is empty, so you divide by zero. The .Net framework then throws a nice DivideByZeroException, which points you to the place in the code were you did not check for the denominator to be zero.
So, then all is well. Until you start calculating with doubles in stead of integers. Then you do not get an exception when you divide by zero. Instead, the double gets one of the following three values:
- PositiveInfinity
- NegativeInfinity
- NaN
The first you get by dividing a positive value by zero, the second by deviding a negative value by zero and the last one by deviding zero by zero. Following the docs, when you want to check whether a double has one of these three values, you cannot check it this way:
d == Double.PositiveInfinity, d == Double.NagativeInfinity, d == Double.NaN
But you have to use these methods instead:
- Double.IsPositiveInfinity(d)
- Double.IsNagativeInfinity(d)
- Double.IsNaN(d)