Skip to content

Instantly share code, notes, and snippets.

@louqash
Last active May 29, 2021 13:53
Show Gist options
  • Save louqash/0d26bdfa485c6d9f0efaa2fb12cbe0fe to your computer and use it in GitHub Desktop.
Save louqash/0d26bdfa485c6d9f0efaa2fb12cbe0fe to your computer and use it in GitHub Desktop.
This gist shows that adding std::numeric_limits<TYPE>::min() to float or double doesn't change the original value, even for as small numbers as 1e-30. This can come useful for calculating logarithms, when one doesn't want `-inf` in the results.
#include <iostream>
#include <limits>
#include <cassert>
#include <cmath>
int main()
{
float f = 1e-30;
float f_plus_min = f + std::numeric_limits<float>::min();
double d = 1e-30;
double d_plus_min = d + std::numeric_limits<double>::min();
assert(f == f_plus_min);
assert(logf(f) > -std::numeric_limits<float>::infinity());
assert(d == d_plus_min);
assert(log(d) > -std::numeric_limits<double>::infinity());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment