[net.lang.c] /-INFINITY and NaN

tribble_acn%uta.csnet@csnet-relay.arpa (David Tribble) (12/23/85)

A question was raised as to how to compare a float (or double) to
the ANSI +/-infinity and Not-a-Number values.  One suggestion was to
use a struct; another way (though arguably not elegant) is-
	#define INFINITY	(*(float*)"\177\200\0\0")
	#define NaN		(*(float*)"\177\277\377\377")
(I'm not certain of the bit patterns, however). The idea is to cast a
string, which is coerced into a char*, into a float*, thus interpreting
the string chars as elements of a float data value.
The same idea can be extended to doubles.
(This works on one compiler that I know of, running on an 8086).

While this may not seem elegant, it has the advantage of not requiring
any structure initilizations.

	David R. Tribble	<tribble_acn@uta>

ark@alice.UucP (Andrew Koenig) (12/25/85)

> A question was raised as to how to compare a float (or double) to
> the ANSI +/-infinity and Not-a-Number values.  One suggestion was to
> use a struct; another way (though arguably not elegant) is-
>	#define INFINITY	(*(float*)"\177\200\0\0")
>	#define NaN		(*(float*)"\177\277\377\377")
> (I'm not certain of the bit patterns, however). The idea is to cast a
> string, which is coerced into a char*, into a float*, thus interpreting
> the string chars as elements of a float data value.
> The same idea can be extended to doubles.
> (This works on one compiler that I know of, running on an 8086).
>
>While this may not seem elegant, it has the advantage of not requiring
>any structure initilizations.
>
>	David R. Tribble	<tribble_acn@uta>

It has the disadvantage of being extremely implementation-specific.

In general, there may be variation from one implementation to another
as to the location of the various bits within a word.  There may also
be alignment problems with this technique on some machines.

gnu@l5.uucp (John Gilmore) (12/27/85)

Sun Unix uses IEEE float.  They provide library routines isnan() and isinf().
Note that there are two infinite values (positive and negative) and many
NaNs, so a simple compare to a single value is not good enough.

These library routines seem to be a good idea, since they can be implemented
for all kinds of float (eg, Vax, IBM) and increase portability.  (A system
without infinites or NaNs would always return false of course.)

ark@alice.UucP (Andrew Koenig) (12/27/85)

> Sun Unix uses IEEE float.  They provide library routines isnan() and isinf().
> Note that there are two infinite values (positive and negative) and many
> NaNs, so a simple compare to a single value is not good enough.

> These library routines seem to be a good idea, since they can be implemented
> for all kinds of float (eg, Vax, IBM) and increase portability.  (A system
> without infinites or NaNs would always return false of course.)

One does have to be a tiny bit careful on architectures where an attempt
to, say, pass a NaN to a subroutine causes a trap.