16.4.1.4 Floating Point Values They Didn’t Talk About In School

Both IEEE 754 floating-point hardware, and MPFR, support two kinds of values that you probably didn’t learn about in school. The first is infinity, a special value, that can be either negative or positive, and which is either smaller than any other value (negative infinity), or larger than any other value (positive infinity). When such values are generated, gawk prints them as either ‘-inf’ or ‘+inf’, respectively. It accepts those strings as data input and converts them to the proper floating-point values internally.

Infinity values of the same sign compare as equal to each other. Otherwise, operations (addition, subtraction, etc.) involving another number and infinity produce mathematically reasonable results.

The second kind of value is “not a number”, or NaN for short.102 This is a special value that results from attempting a calculation that has no answer as a real number. In such a case, programs can either receive a floating-point exception, or get NaN back as the result. The IEEE 754 standard recommends that systems return NaN. Some examples:

sqrt(-1)

This makes sense in the range of complex numbers, but not in the range of real numbers, so the result is NaN.

log(-8)

−8 is out of the domain of log(), so the result is NaN.

NaN values are strange. In particular, they cannot be compared with other floating point values; any such comparison, except for “is not equal to”, returns false. NaN values are so much unequal to other values that even comparing two identical NaN values with != returns true!

NaN values can also be signed, although it depends upon the implementation as to which sign you get for any operation that returns a NaN. For example, on some systems, sqrt(-1) returns a negative NaN. On others, it returns a positive NaN.

When such values are generated, gawk prints them as either ‘-nan’ or ‘+nan’, respectively. Here too, gawk accepts those strings as data input and converts them to the proper floating-point values internally.

If you want to dive more deeply into this topic, you can find test programs in C, awk and Python in the directory awklib/eg/test-programs in the gawk distribution. These programs enable comparison among programming languages as to how they handle NaN and infinity values.


Footnotes

(102)

Thanks to Michael Brennan for this description, which we have paraphrased, and for the examples.