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?
NaN: “A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to the value returned by Double.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With