I want to add the smallest possible value of a float to a float. So, for example, I tried doing this to get 1.0 + the smallest possible float:
float result = 1.0f + std::numeric_limits<float>::min();
But after doing that, I get the following results:
(result > 1.0f) == false (result == 1.0f) == true
I'm using Visual Studio 2015. Why does this happen? What can I do to get around it?
The smallest is sys. float_info. min (2.2250738585072014e-308) and the biggest is sys.
Floating point numbers have limited precision.
If you want the next representable value after 1, there is a function for that called std::nextafter
, from the <cmath>
header.
float result = std::nextafter(1.0f, 2.0f);
It returns the next representable value starting from the first argument in the direction of the second argument. So if you wanted to find the next value below 1, you could do this:
float result = std::nextafter(1.0f, 0.0f);
Adding the smallest positive representable value to 1 doesn't work because the difference between 1 and the next representable value is greater than the difference between 0 and the next representable value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With