#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.
source share