I have a variable float slope
that sometimes will have a value of nan
when printed out since a division by 0
sometimes happens.
I am trying to do an if-else for when that happens. How can I do that? if (slope == nan)
doesn't seem to work.
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 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.
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating-Point Number Classification Functions).
CPP. Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.
Two ways, which are more or less equivalent:
if (slope != slope) {
// handle nan here
}
Or
#include <math.h>
...
if (isnan(slope)) {
// handle nan here
}
(man isnan
will give you more information, or you can read all about it in the C standard)
Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2
if you're just going to end up using atan
on the slope instead of doing some other computation).
Nothing is equal to NaN
— including NaN
itself. So check x != x
.
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