How to detect NaN's
Dan McCoy
mccoy at pixar.com
Thu Jun 20 09:58:01 AEST 1991
In article <1991May30.204332.16506 at litwin.com> vlr at litwin.com (Vic Rice) writes:
>How can I test a variable for the presence of a NaN or Infinity ???
Others have answered this question if detecting these values is what
you really want.
But if what you really want is to write code that won't fail when presented
with NaN's and Inf's, it's often possible to just write code so that
sensible behaviour just falls out.
For instance, a NaN will fail any test. It's not equal to anything, including
itself, and it's not greater than anything or less than anything.
If you write:
if (x > maxvalue) outofrange();
x=NaN will appear to be in range, since it will fail the ">" test.
But if you write:
if (!(x <= maxvalue)) outofrange();
then x=NaN will be out of range since it failed the "<=" test.
This type of defensive coding allows you to write bullet-proof code without
having to clog it up with explicit NaN checks all over the place.
(I noticed the cross-post to comp.lang.fortran just before sending.
The concept applies just as well in Fortran.
However my Fortran is so rusty, I better let the example stand in C.)
Dan McCoy Pixar ...!ucbvax!pixar!mccoy
More information about the Comp.unix.ultrix
mailing list