|If this division leads to an overflow, the result will be stored as "NaN", am I right?|
In that case, you would get some kind of infinity. +/- inf
is distinct from NaN.
|Are there other cases in floating point calculations where you receive NaN as a result?|
Yes. NaNs occur generally when computing some indeterminate expression (e.g., dividing zero by +/- inf
|Can I, in the following, check whether the resulting double is == NaN in order to see whether something went wrong?|
No: assuming IEEE754, NaNs never
compare equal with anything, even other NaNs. For instance, given a floating point value x
, the expression x != x
is any NaN
Generally prefer std::isnan()
to test for NaN
. This avoids unwanted side-effects in the floating point environment
, if access to it is enabled.
The floating-point environment is a thread-local state-space. Its status flags control the current rounding behavior and track floating-point exceptions. For example, if an overflow occurs, an exception flag is set indicating an overflow occurred. Some operations on NaNs can set exception flags, possibly including self-comparison - but not std::isnan()
It's possible to access the floating point environment if you've said
#pragma STDC FENV_ACCESS ON
in your program. Explicitly opting-in allows the compiler to bother with it only when necessary.