NaN

RS 2007-02-23: NaN is "Not a Number", a sort-of-valid floating point value from Tcl 8.5. Here are experiments:

 (bin) 13 % set y [expr sqrt(-1)]
 -NaN
 (bin) 14 % expr {$y == $y} ;# the only value that is not equal to itself :^)
 0
 (bin) 15 % expr {$y eq $y}
 1

male 2007-02-23: Sorry, but using tclkit(sh)? 8.5a4 ...

 % expr {sqrt(-1)}
 domain error: argument not in valid range

RS I used tclkit 8.5a4 as well, on Win XP. So the patchlevel doesn't yet tell the full story :( Do the Inf examples work for you?

male yes, the Inf examples all work for me. But ... my tclkit(sh)? executables are bit older, some of the first built.

LV Okay, so I use the base-tcl8.5-thread-solaris-sparc (a tclkit) from ActiveTcl 8.5 beta (Tcl 8.5a5), as well as built myself the latest CVS head for Tcl 8.5a6 on SPARC Solaris. In both cases, I get the domain error, not the -NaN.

I also see the domain error using just standard tclsh from 8.5.4 or 8.6 cvs head..


RS 2007-09-28: With 8.5b1 on WinXP, NaN is gone too :(

 % set n [expr sqrt(-1.)]
 domain error: argument not in valid range

Philip Smolen It seems that NaN isn't completely gone. expr hides it. If you say ::tcl::mathfunc::sqrt -1 you still get "-NaN" as a result. TCL8.5

But as everything is a string, we can still demonstrate the remarkable property

 % set n NaN
 NaN
 % expr {$n == $n}
 0

See also expr - Inf


AM (23 february 2009) While this works nicely from the Tcl side of things, you may run into trouble when the NaN comes from a C (compiled) extension that uses, say, the standard sprintf() function to pass the value to Tcl. While sprintf() is a standard function, the representation of NaN by the various compilers is not. Here are a few possibilities: NaN, nan, -1.#IND, 1.#QNAN

Quite a few others seem to exist as well - it is, in short, rather messy.

DKF: Try this simple method. If you know a value should be a number, try to parse it as such. If you fail, it's a NaN.

AM Yes, that seems to be the simplest and most straightforward approach. See [L1 ] for more gory details (as KBK pointed out to me).


AM (20 may 2010) Here is a small procedure to detect if a value is a "not-a-number" or not (that is, if it is a proper number):

proc isnan {x} {
    if { ![string is double $x] || $x != $x } {
        return 1
    } else {
        return 0
    }
}

(This works for Tcl 8.4 and previous as well as for Tcl 8.5 and later)