How to by a given value like 0.00...001 find the position of 1?
I have a sample code like this:
constexpr int PrecisionFromDouble(double val)
{
int d = 1.0 / val;
int log = 0;
while (true)
{
d = d / 10;
if (d == 0)
break;
++log;
}
return log;
}
It works with the following values:
static_assert(PrecisionFromDouble(0.0001) == 4);
static_assert(PrecisionFromDouble(0.001) == 3);
static_assert(PrecisionFromDouble(0.01) == 2);
static_assert(PrecisionFromDouble(0.1) == 1);
static_assert(PrecisionFromDouble(1.0) == 0);
but does not work with 0.00001, because d
becomes 9999.
EDIT1:
It works a bit better with std::round
in the first line of the function:
int d = static_cast<int>(std::round(1.0 / val));
this should work with the most double literals like 0.00..001