6

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?

erip
  • 16,374
  • 11
  • 66
  • 121
ctanakul
  • 131
  • 6
  • Are you asking how to detect if a division will result in overflow? https://stackoverflow.com/questions/15655070/how-to-detect-double-precision-floating-point-overflow-and-underflow – Jive Dadson Jul 12 '18 at 01:06
  • 2
    @It'scominghome, Epsilon isn't quite right. The step to the next value after 1 isn't the same thing as the step to the next value after 0. For me, the difference between the two is quite pronounced (e-16 vs. e-308). – chris Jul 12 '18 at 01:06
  • 1
    What exactly are you doing to avoid NaN? Simply replacing a zero divisor with a small (positive) value is not necessarily a correct approach (it depends on the context). A more correct approach might be to deal with NaN rather than avoiding it. – JaMiT Jul 12 '18 at 04:47
  • 1
    @JaMiT Thanks for pointing this out. For my application, just avoiding NaN is clearly not enough. It moves result out of the proper path. – ctanakul Jul 12 '18 at 16:10

2 Answers2

5

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
-1

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();  
Nathan majicvr.com
  • 950
  • 2
  • 11
  • 31
  • 1
    The exact maximum and minimum for 'float' isn't set by the standard. Implementations can use any conforming floating point representation. – François Andrieux Jul 12 '18 at 03:26