Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how can I test if a number is power of ten?

I want to test if a number double x is an integer power of 10. I could perhaps use cmath's log10 and then test if x == (int) x?

edit: Actually, my solution does not work because doubles can be very big, much bigger than int, and also very small, like fractions.

like image 917
Giovanni Funchal Avatar asked Mar 31 '10 09:03

Giovanni Funchal


People also ask

How do you check if a number is a power of 10?

Number is a power of 10 if it's equal to 10, 100, 1000 etc. 1 is also 0-th power of 10. Other numbers like 2, 3, 11, 12 etc. are not powers of 10.

How do you check if a number is a power of something?

A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not.

How do you find the power of 10?

Thus, shown in long form, a power of 10 is the number 1 followed by n zeros, where n is the exponent and is greater than 0; for example, 106 is written 1,000,000. When n is less than 0, the power of 10 is the number 1 n places after the decimal point; for example, 10−2 is written 0.01.


2 Answers

A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.

This has the advantage that you will get a "hit" if and only if your number is exactly the closest possible IEEE double to some power of 10. If this isn't what you want, you need to be more precise about exactly how you would like your solution to handle the fact that many powers of 10 can't be exactly represented as doubles.

The best way to construct the table is probably to use string -> float conversion; that way hopefully your library authors will already have solved the problem of how to do the conversion in a way that gives the most precise answer possible.

like image 103
Paul Crowley Avatar answered Oct 14 '22 22:10

Paul Crowley


Your solution sounds good but I would replace the exact comparison with a tolerance one.

double exponent = log10(value);
double rounded = floor(exponent + 0.5);
if (fabs(exponent - rounded) < some_tolerance) {
    //Power of ten
}
like image 34
Andreas Brinck Avatar answered Oct 14 '22 23:10

Andreas Brinck