Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding smallest possible float to a float

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?

like image 275
gsemac Avatar asked Dec 24 '16 23:12

gsemac


People also ask

How small can a float get?

The smallest is sys. float_info. min (2.2250738585072014e-308) and the biggest is sys.

Does float have limited precision?

Floating point numbers have limited precision.


1 Answers

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.

like image 188
Benjamin Lindley Avatar answered Sep 21 '22 03:09

Benjamin Lindley