Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way of checking if Double is "NaN"

When calling Double.IsNaN() with Double.PositiveInfinity as argument, the result is false. This is against my intuition since infinity is not a number. Apparently "NaN" only exists in terms of a constant in .NET, is this described by the IEEE standard or is it a custom implementation detail? Is there a shorter way to check if a Double is "NaN" than:

(Double.IsNaN(d) || Double.IsPositiveInfinity(d) || Double.IsNegativeInfinity(d)) 

or

(Double.IsNaN(d) || Double.IsInfinity(d)) 
like image 251
Leopold Asperger Avatar asked Jul 11 '14 12:07

Leopold Asperger


People also ask

How do you know if something is a 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.

How do I know if my float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

Is Double NaN?

IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN). Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False. Code: To demonstrate the Double.


2 Answers

As MSDN says, NaN means that result is undefined. With infinities result is defined:

A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, as the following example shows. (But note that dividing a non-zero number by zero returns either PositiveInfinity or NegativeInfinity, depending on the sign of the divisor.)

So, it's not good idea to tread infinities as NaN. You can write extension method to check if value is not NaN or infinity:

// Or IsNanOrInfinity public static bool HasValue(this double value) {     return !Double.IsNaN(value) && !Double.IsInfinity(value); } 
like image 193
Sergey Berezovskiy Avatar answered Sep 24 '22 00:09

Sergey Berezovskiy


You no longer need an extension from SergeyBerezovskiy answer.

double has IsFinite() method to check if a double is a finite number (is not NaN or Infinity):

double.IsFinite(d) 

See source code in .Net Framework and .Net Core

like image 32
Roman Marusyk Avatar answered Sep 21 '22 00:09

Roman Marusyk