While writing some test cases, and some of the tests check for the result of a NaN.
I tried using std::isnan
but the assert failes:
Assertion `std::isnan(x)' failed.
After printing the value of x
, it turned out it's negative NaN (-nan
) which is totally acceptable in my case.
After trying to use the fact that NaN != NaN
and using assert(x == x)
, the compiler does me a 'favor' and optimises the assert away.
Making my own isNaN
function is being optimised away as well.
How can I check for both equality of NaN and -NaN?
If the argument is negative, returns -1 . If the argument is positive zero, returns 0 . If the argument is negative zero, returns -0 . Otherwise, NaN is returned.
There is no meaningful notion in which a value can be +NaN or -NaN, as NaN does not have a sign; "treating the values as distinct" is a bug in a program, if the intent is to run on IEEE-754 arithmetic.
What are NaN values? NaN or Not a Number are special values in DataFrame and numpy arrays that represent the missing of value in a cell. In programming languages they are also represented, for example in Python they are represented as None value.
NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.
This is embarrassing.
The reason the compiler (GCC in this case) was optimising away the comparison and isnan
returned false
was because someone in my team had turned on -ffast-math
.
From the docs:
-ffast-math Sets -fno-math-errno, -funsafe-math-optimizations, -fno-trapping-math, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans and fcx-limited-range. This option causes the preprocessor macro __FAST_MATH__ to be defined. This option should never be turned on by any -O option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions.
Notice the ending sentence - -ffast-math
is unsafe.
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