How many places of precision does a float
have between 1.0f
and 0.0f
such that every value could be uniquely represented?
For
std::numeric_limits::digits10
From http://en.cppreference.com/w/cpp/types/numeric_limits/digits10
The standard 32-bit IEEE 754 floating-point type has a 24 bit fractional part (23 bits written, one implied), which may suggest that it can represent 7 digit decimals (24 * std::log10(2) is 7.22), but relative rounding errors are non-uniform and some floating-point values with 7 decimal digits do not survive conversion to 32-bit float and back: the smallest positive example is 8.589973e9, which becomes 8.589974e9 after the roundtrip. These rounding errors cannot exceed one bit in the representation, and digits10 is calculated as (24-1)*std::log10(2), which is 6.92. Rounding down results in the value 6.
Edit2:
This shows that the number is not 7 but only 6 digits for any float, just like the std::numeric_limits
call will tell.
float orgF = 8.589973e9;
int i = orgF;
float f = i;
assert(f == orgF);
This will fail as the roundtrip changes the value.
So if we are only looking for numbers between 1.0 and 0.0, positive the answer is 7, as the lowest positive number which has a problem is 8.589973e9.