This page will answer the following questions.
- My program just printed 1. # IND or 1. # INF (on Windows) or nan or inf (on Linux). What happened?
- How do you know if a number is really a number, not NaN or infinity?
- How can I find out more runtime information about NaN types and infinity?
- Do you have sample code to show how this works?
- Where can I find out more?
These questions are related to floating point exceptions. If you get some strange non-numeric output in which you expect a number, you either exceeded the final limits of floating point arithmetic, or asked to get the result undefined. To keep things simple, I will work with a double floating point type. Similar remarks are retained for float types.
Debugging 1. # IND, 1. # INF, nan and inf
If your operation will generate a larger positive number than can be stored in double, the operation will return 1. # INF on Windows or inf on Linux. Similarly, your code will return -1. # INF or -inf if the result is a negative number that is too large to hold in double. Dividing a positive number by zero creates positive infinity and dividing a negative number by zero creates negative infinity. The sample code at the end of this page will demonstrate some operations that produce infinity.
Some operations do not have mathematical meaning, for example, they take the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but double represents a real number, and therefore there is no double representation of the result). The same is true for the logarithms of negative numbers. Both sqrt (-1.0) and log (-1.0) return NaN, a generic term for "number" that is "not a number". Windows displays NaN as -1. # IND ("IND" for "indefinite"), while Linux displays nan. Other operations that return NaN include 0/0, 0 * โ, and โ / โ. See the sample code below.
In short, if you get 1. # INF or inf, find overflow or division by zero. If you get 1. # IND or nan, look for illegal transactions. Maybe you just have a mistake. If it is more subtle and you have something that is difficult to calculate, see the section โAvoid Overflows, Underutilization, and Loss of Accuracyโ. This article provides tricks for calculating results that have an intermediate overflow when calculating directly.