views:

139

answers:

7

Many languages have an isNaN() function. I am asking myself: why check for not being a number?

Is the reason purely logical or is it faster to check for not a number instead of is a number?

Note that this is a pure question of understanding. I know that I can negate isNaN() to achieve an isNumber() function for example.
However I am searching for a reason WHY we are checking for not a number?

+7  A: 

In computing, NaN (Not a Number) is a value of numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.

Wiki Article

Because Not a Number is a special case of an expression.

You can't just use 0 or -1 or something like that because those numbers already have meanings.

Not a Number means something went awry in a calculation and a valid number cannot be computed out of it.

It's on the same line of thinking as having null. Sure, we could assign an arbitrary numerical value to mean null but it would be confusing and we'd hit all sorts of weird errors on corner cases.

Robert Greiner
+1  A: 

It is a way to report an error condition (mathematically undefined or outside of technical limits).

Henk Holterman
+3  A: 

'Not a Number' is the result of specific floating point calculations. It's not about "hey, is this variable holding 120 or "abc"?'

Habbie
A: 

Many languages have special representations if the result of a computation is not representable by a number, for example NaN and Inf. So isNaN() checks, if a result is actually a number or the special marker for NaN.

Juri Robl
+1  A: 

isThisCaseExceptional seems more reasonable to me than isEverythingNormal because I'm likely to write

possible_number = some_calculation();

if (inNaN(possible_number)) handle_the_surprise;

// .. keep going 

instead of

possible_number = some_calculation();

if (inANumber(possible_number)) {

   // .. keep going 

} else {
   // handle the surprise
}
dmckee
+2  A: 

The check is for whether it is not a number, because the assumption is that it is a number. NaN is the exceptional case when you're expecting a numeric value, so it makes sense to me that it is done this way. I'd rather check for isNaN infrequently than check if a value isNum frequently, after all.

Alex JL
A: 

NaNs are used for:

  • Nonreal or undefined values.
  • Error handling. Initializing a variable with NaN allows you to test for NaN and make sure it has been set with a valid value.
  • Objects that ignore a member or property. For example, WPF uses NaN to represent the Width and Height of visual elements that do not define their own size.
Khyad Halda