I'm writing a code to prevent the zero denominator/divisor to avoid NaN value as a result of the division.
I wonder what could be the least possible denominator value in double in C++ and how to find or what's the reason for that?
I'm writing a code to prevent the zero denominator/divisor to avoid NaN value as a result of the division.
I wonder what could be the least possible denominator value in double in C++ and how to find or what's the reason for that?
Well, the smallest positive(a) normalised double
in C++ can be obtained with std::numeric_limits<double>::min()
(from the <limits>
header).
However, while you may be able to use that to prevent NaN
values(b), it probably won't help with overflows. For example:
std::numeric_limits<double>::max() / 1.0 => ok
std::numeric_limits<double>::max() / 0.5 => overflow
Preventing that will depend on both the denominator and the numerator.
As for why that is the case, it's because C++ uses IEEE-754 double-precision format for its double
types - it's a limitation of that format.
(a) I've chosen positive values here, the smallest value could be interpreted as the most negative, in which case it would be read as -std::numeric_limits<double>::max()
. But, given your intent is to avoid NaN
, I suspect my assumption is correct.
(b) I'm not entirely sure how you intend to do this, which is why I also discuss overflows - you may want to make it clearer in your question.
The smallest possible float is 1.17549e-38. To expand upon It's coming home's comment, see the answer from here:
#include <limits>
//...
std::numeric_limits<float>::max(); // 3.40282e+38
std::numeric_limits<float>::min(); // 1.17549e-38
std::numeric_limits<float>::infinity();
The float
in the above code can be replaced by any data type you want, ie:
std::numeric_limits<int>::min();