NaN's (was Re: FLOATING NULL?)

Stephen Clamage steve at taumet.com
Sun Jun 2 04:22:59 AEST 1991


sarima at tdatirv.UUCP (Stanley Friesen) writes:

>In article <2726 at root44.co.uk> gwc at root.co.uk (Geoff Clare) writes:
>>I agree there is no standard way of generating NaN (although sqrt(-1.0)
>>is your best bet).  However, there is a standard way of testing for NaN.
>>If x is a floating point variable, then (x != x) will be TRUE if and
>>only if x has the value NaN.

>But what if the compiler notices you are asking for a self comparison and
>optimizes it away?  Then this will fail unless x is volatile.

>Since NaN's fall in the area of unspecified/undefined behavior I believe
>that such an optimization is legal under the ANSI standard.

The IEEE standard for floating-point recommends a set of functions to
be made available.  Among these are functions to classify a value
as NaN, Infinity, Zero, Denormalized, Normalized, and so on.  Most
implementations I am familiar with provide this functionality,
although there are no standard names for the functions.  Such
implementations often provide predefined identifiers (such as _NaN,
_Infinity, etc) to allow you to generate these values.  There is a
group working on proposing standard extensions to C for numerical
work.  Perhaps they will recommend standards in this area.

In the mean time, you can write your own "standard" functions and macros,
and provide versions of them for each system you use.  If the system
provides the functions you need, you #define your "standard" functions
to be the system functions.  Otherwise, you write your function as an
interface to what the system provides, or write your own from scratch.
This is all rather easy to do, but is system-specific.

Some of the suggestions in this thread for portable ways to generate or
test for a NaN are not all that portable.  For example, sqrt(-1.0) might
generate a trap, and in any case might not return a NaN.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list