Last active
May 29, 2021 13:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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