Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have "is not a Number" (isNan) functions?

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?

like image 379
Luis Nell Avatar asked Dec 08 '22 01:12

Luis Nell


1 Answers

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.

like image 131
Robert Greiner Avatar answered Dec 11 '22 10:12

Robert Greiner