How can I round up to the nearest power of a number?

1.6k Views Asked by At

I'm sorry if I got the terminology wrong. Let me explain with an example.

Given a multiplier (we'll say 2.5), I need an equation or algorithm to find what power level a number resides in (preferably calculated, not a loop).

Level 0: < 2.5
Level 1: < 6.25 (2.5 ^ 2)
Level 2: < 15.625 (2.5 ^ 3)

And input of 8 would give an output of 15.625, as it is greater than or equal to 6.25 and less than 15.625.

Please let me know if my question is unclear. Thanks guys.

2

There are 2 best solutions below

6
On BEST ANSWER

If $b$ is the base ("multiplier", $2.5$ in the example) and $x$ is the number to be tested, the next power of $b$ is $$b^{\left\lfloor\log_b x\right\rfloor+1}$$ where $\log_b x$ is the logarithm to base $b$ and $\lfloor x\rfloor$ is the floor function.

If you don't have access to arbitrary logarithms, use $$\log_b x = \frac{\log x}{\log b}$$ where the logarithm on the right can be whatever logarithm is available to you — typically either the natural logarithm, or the base 10 logarithm —, but it must be the same for the numerator and denominator.

Edit note: I corrected the formula after I noticed that when your number already is a power of the given base, you want the next one. The pre-edit formula would have given the same power for this case (so for example, $6.25$ would have resulted in $6.25$ with the old formula, but gives $15.625$ with the corrected one. Note that for any other numbers, both give the same result.

2
On

I think the formula $2.5^{\lceil \log_{2.5}x \rceil}$ is the one you want. So for your example with $x=8$ we have,

$$2.5^{\lceil \log_{2.5}x \rceil} = 2.5^{\lceil \log_{2.5}8 \rceil} = 2.5^{\lceil 2.26941\dots \rceil} = 2.5^3 = 15.625.$$

EDIT: This formula might be a bit off in certain edge cases since you have $<$'s and not $\leq$'s. In particular, if $\log_{2.5}x$ is an integer, you would want to add $1$ to exponent. Whether or not you would want to do that is moreso based on the context of the problem you are trying to solve though.