Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ std::numeric_limits<float>::max() be accurately stored in a float and later compared?

I know that some values are unable to be easily defined in floats, and are only 'approximated', making direct 'equals' comparisons frequently not work.

Can std::numeric_limits::max be stored in a float accurately, and will this code function as expected?

float myFloat = std::numeric_limits<float>::max();

//...later...
if(myFloat == std::numeric_limits<float>::max())
{
    //...myFloat hasn't changed...
}
like image 409
Jamin Grey Avatar asked Dec 27 '22 08:12

Jamin Grey


1 Answers

For a given (non-NaN) float variable, f, it is guaranteed that f == f is always true. Since myFloat gets set to some float value, of course it will compare equal to that same value.

You are apparently thinking of cases such as:

float f1 = 0.1;
float f2 = 1.0/10;
assert( f1 == f2 );

which might fail, but this will not fail:

float f1 = 0.1;
float f2 = 0.1;
assert( f1 == f2 );

Although the value stored in the variables may not be exactly equal to 0.1 but may have a different value instead, you will get the same value for both variables, and so they will compare equal.

Whatever value numeric_limits<float>::max() happens to return, it is a fixed value that will compare equal to itself.

like image 123
Jonathan Wakely Avatar answered Jan 30 '23 12:01

Jonathan Wakely