I currently have some code where I have to normalize a vector of doubles (divide each element by the sum). When debugging, I see sometimes that the elements in the vector are all 0.0. If I then 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 normalizing the vector for the cases when the sum is either 0.0 or a denormalized number. The only way I could think of handling these two cases is to check if the sum is less than 'epsilon', where epsilon is some small number (but I'm not sure how small to make epsilon).
I have 2 questions:
#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.
}
Addendum
Since you are trying to normalize a vector, I would venture 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.
sqrt(max_double)
you will get infinities.sqrt(min_double)
you will get underflow.C99 provides fpclassify
to detect denormalized number. It's also provided 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) {
// ...
}
You can use a flag while you take the sum to ensure that not every element is equal to 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.