Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check NaN number [duplicate]

Tags:

Is it possible to check if a number is NaN or not?

like image 279
MBZ Avatar asked Aug 09 '10 03:08

MBZ


People also ask

How do I know if a number is NaN?

isNaN() Method: To determine whether a number is NaN, we can use the isNaN() function. It is a boolean function that returns true if a number is NaN otherwise returns false.

Does Isnull check for NaN?

Detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing ( NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike).

How do you test a NaN?

isNaN() method to check if a number is NaN, e.g. if (Number. isNaN(num)) {} . The Number. isNaN() method will return true if the provided value is NaN and has a type of number .

Is NaN == NaN?

Yeah, a Not-A-Number is Not equal to itself. But unlike the case with undefined and null where comparing an undefined value to null is true but a hard check(===) of the same will give you a false value, NaN's behavior is because of IEEE spec that all systems need to adhere to.


2 Answers

Yes, by use of the fact that a NaN is not equal to any other number, including itself.

That makes sense when you think about what NaN means, the fact that you've created a value that isn't really within your power to represent with "normal" floating point values.

So, if you create two numbers where you don't know what they are, you can hardly consider them equal. They may be but, given the rather large possibility of numbers that it may be (infinite in fact), the chances that two are the same number are vanishingly small :-)

You can either look for a function (macro actually) like isnan (in math.h for C and cmath for C++) or just use the property that a NaN value is not equal to itself with something like:

if (myFloat != myFloat) { ... } 

If, for some bizarre reason, your C implementation has no isnan (it should, since the standard mandates it), you can code your own, something like:

int isnan_float (float f) { return (f != f); } 
like image 185
paxdiablo Avatar answered Sep 20 '22 04:09

paxdiablo


Under Linux/gcc, there's isnan(double), conforming to BSD4.3.

C99 provides fpclassify(x) and isnan(x).
(But C++ standards/compilers don't necessarily include C99 functionality.)

There ought to be some way with std::numeric_limit<>... Checking...

Doh. I should have known... This question has been answered before... Checking if a double (or float) is NaN in C++ Using NaN in C++? http://bytes.com/topic/c/answers/588254-how-check-double-inf-nan

like image 33
Mr.Ree Avatar answered Sep 23 '22 04:09

Mr.Ree