Can C ++ std :: numeric_limits <float> :: max () be neatly stored in a float and later compared?
I know that some values ββcannot be easily determined in floats and are only "approximate", so direct comparisons of "peers" often do not work.
Can std :: numeric_limits :: max be stored in the float exactly, and will this code function properly?
float myFloat = std::numeric_limits<float>::max(); //...later... if(myFloat == std::numeric_limits<float>::max()) { //...myFloat hasn't changed... } For a given (non-NaN) variable, float f guaranteed that f == f always true. Since myFloat set to some kind of float , of course, it will be compared with the same value.
You are apparently thinking of cases such as:
float f1 = 0.1; float f2 = 1.0/10; assert( f1 == f2 ); which may fail, but this will not be done:
float f1 = 0.1; float f2 = 0.1; assert( f1 == f2 ); Although the value stored in the variables may not be exactly 0.1 , but may have a different value instead, you will get the same value for both variables, and therefore they will compare equal ones.
Whatever value of numeric_limits<float>::max() is returned, it is a fixed value that will be compared with itself.
Yes.
numerical constraints are the class template, and max is the static method:
template <class T> class numeric_limits { public: ... static T max() throw(); //constexpr if using C++11 ... }; So, for the float type, you actually use std::numeric_limits<float>::max() and just compare the two floats of equal value (until you use myFloat before comparison). The value max () will be a sequential float for your platform and will have an equivalent binary representation for itself.
The main problem you will have to face is serializing and deserializing on different platforms using a different binary floating point representation. Therefore, if you try to serialize the variable myFloat on some other machine, you will try to compare the result of the deserialized value directly with numeric_limits :: max ():
if( myFloat == std::numeric_limits<float>::max() ) The result may not be valid. Then you will need to code your concept of βMAXβ in your binary representation and interpret it explicitly as you want.
Yes but
myFloat += someSmallFloat; cannot change the value of myFloat .
If you want to learn more, there is a great tutorial on floating point representations called What Every Computer Scientist Should Know About Floating Point Arithmetic .