Someone sent me a question yesterday that boiled down to the difference between kinds of numeric exceptions. I’ll give my response below, but first a little background.
Numeric exceptions occur when a computer does some operation on a number that produces an error. The abstraction that lets us think of computer numbers as mathematical numbers has sprung a leak. On Windows you may see output that looks like
1.#INF. On Linux you may see
inf. These values do not correspond to mathematical real numbers but instead are codes saying what went wrong.
If you’ve heard of NaNs (NaN stands for “not a number”) you might call every numerical exception a NaN. That’s reasonable since indeed an exception is “not a number”, or at least not an ordinary number. The problem is that NaN has a more restricted technical meaning that excludes some kinds of exceptions.
An infinite values is an exception but not a NaN. The difference is important. Some mathematical operations still make sense on an infinite value, but no operations make sense on a NaN. For example, if two floating point values are infinite and have the same sign, they are equal. But a NaN cannot equal anything, not even itself. So in C, if
x is a
double then the test
x == x will return true if
x is infinite but not if
x is a NaN.
The question that motivated this post had assumed that an infinite value was a NaN.
No, and infinity is not a NaN.
It all makes sense when you think about it. A NaN is a computer’s way of saying “I don’t know what else to do.” An infinity is the computer saying “It’s bigger than I can handle, but I’ll preserve the sign.”
For example, let
xbe the largest finite number a computer can represent. What is
2*x? Too big to represent, but it’s positive, so it’s +infinity. What’s
-2*x? It’s -infinity.
But what is
sqrt(-1)? It’s not big, so it’s not infinity. It’s just complex. Nothing else makes sense, so the computer returns NaN.
Windows displays infinite results as
-1.#INF depending on the sign. Linux displays
-inf. Windows displays NaNs as
-1.#IND (“ind” for “indeterminate”) and Linux displays
For more details see these notes:
IEEE floating point exceptions in C++