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

c++, floating-accuracy

Solution

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.

Problem

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... } ```

Original source