Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why float.NaN != double.NaN in C#?

Tags:

c#

.net

nan

Why float.NaN != double.NaN ?

while float.PositiveInfinity == double.PositiveInfinity and float.NegativeInfinity == double.NegativeInfinity are equal.

EXAMPLE:

bool PosInfinity = (float.PositiveInfinity == double.PositiveInfinity); //true bool NegInfinity = (float.NegativeInfinity == double.NegativeInfinity); //true  bool isNanEqual = (float.NaN == double.NaN);  //false, WHY? 
like image 900
Javed Akram Avatar asked Mar 06 '11 05:03

Javed Akram


People also ask

Can double Be NaN?

NaN: “A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.

Why does NaN float?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis.

What does double NaN return?

All numeric operations with NaN as an operand produce NaN as a result. Reason behind this is that NaN is unordered, so a numeric comparison operation involving one or two NaNs 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.


1 Answers

NaN is never equal to NaN (even within the same type). Hence why the IsNaN function exists:

Double zero = 0; // This will return true. if (Double.IsNaN(0 / zero))  {     Console.WriteLine("Double.IsNan() can determine whether a value is not-a-number."); } 

You should also be aware that none of the comparisons you've shown are actually occurring "as is". When you write floatValue == doubleValue, the floats will actually be implicitly converted to doubles before the comparison occurs.

like image 74
Damien_The_Unbeliever Avatar answered Sep 21 '22 04:09

Damien_The_Unbeliever