Check for null or denormalized number in C ++

I currently have a code in which I have to normalize the doubles vector (divide each element by the sum). When debugging, sometimes I see that the elements in the vector are equal to 0.0. If I take the sum of the elements, I get either 0.0 or 4.322644347104e-314 # DEN (which I recently found out was a denormalized number). I would like to prevent the normalization of the vector for cases where the sum is either 0.0 or a denormalized number. The only way I could handle these two cases is to check if the amount of epsilon is less, where epsilon is a small number (but I'm not sure how little epsilon is to make).

I have 2 questions:

  • What is the best way to account for these cases?
  • Does the value of a machine with a denormalized number depend?
+4
source share
3 answers
#include <limits> #include <cmath> double epsilon = std::numeric_limits<double>::min(); if (std::abs(sum) < epsilon) { // Don't divide by sum. } else { // Scale vector components by sum. } 

Adding
Since you are trying to normalize a vector, I would risk that your sum is the sum of the squares of the vector elements, conceptually

 double sum = 0; for (unsigned int ii = 0; ii < vector_size; ++ii) { sum += vector[ii]*vector[ii]; } sum = std::sqrt(sum); 

There are three problems with the above.

  • If any of these vector components are larger than sqrt(max_double) , you get infinity.
  • If any of these vector components is smaller than sqrt(min_double) , you will get an underflow.
  • Even if the numbers behave well (between 2 * 10 -154 and 10 154 in magnitude), the above is problematic if the values ​​vary greatly (a factor of 10 6 ). You will need a more complex hypotenuse function, if so.
+9
source

C99 provides fpclassify to detect a denormalized number. It is also equipped with C ++ 0x and Boost.Math.

 // C++0x #include <cmath> using std::fpclassify; // Boost //#include <boost/math/special_functions/fpclassify.hpp> //using boost::math::fpclassify; if(fpclassify(sum) == FP_SUBNORMAL) { // ... } 
+6
source

You can use the flag while you take the amount to ensure that not every element is 0.

0
source

All Articles