Reputation: 2060
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
Upvotes: 1
Views: 191
Reputation: 11311
This one works (corrected after phuclv
's comment):
constexpr int PrecisionFromDouble(double val)
{
int log = 0;
unsigned long long m(10);
while (1. / m >= val)
log++, m*= 10;
return log;
}
Upvotes: 0
Reputation: 3744
I think you can use log10
#include <math.h>
constexpr int PrecisionFromDouble(double val)
{
return -(int)log10(val);
}
Upvotes: 1
Reputation:
main(){
int error;
float fvalue=0.0001;
char *cstr = ftoa(dvalue,&error);
string str(cstr);
size_t position = str.find_first_of("1",0);
cout << position <<endl;
}
Upvotes: 1