[Math] Find closest power of 2 to a specific number

algebra-precalculus

This question is weird and it's not a homework question. I couldn't come up with anything substantial, so sorry if you think that I should have posted my tried methods (I have tried but most of them were fails).

So, suppose I have a number $n$. Its parity doesn't matter(whether it is even or odd is to no interest to us). Just by having $n$ is there a way to find $2^m$ where when $2$ raised to the power of $m$, it is the value that is closest to $n$?

Like for example, if $n = 7$ then the closest power of $2$ is $2^3$ which is $8$.

But my question is:

Is there a function with which I can calculate this?

If there was something that I failed to represent and as a result, you didn't understand, please comment. Also, I don't know the tag to put this in, somebody please help me.

Best Answer

This is not a weird question at all, but I don't think this is the best forum for a lesson on logarithms. You'll find lots of stuff on the Web if you Google "logarithm." I suggest you look at some of the lessons, and come back here if you have questions. In the meantime, I'll explain how to answer the question.

What you want is the base-$2$ logarithm. For example $$\log_2 7=x$$ means the same thing as $$2^x=7.$$ Now, to compute $\log_2{7}$ we can use WolframAlpha and find $$\log_2{7}\approx2.8$$ This tells us that the $n$ we seek is either $2$ or $3$. While it's easy to guess that the answer is $3$ in this case, until you know more about logarithms, I suggest you just compute bot $2^2$ and $2^3$ and see which is closer. It's not always true that you can just take the integer closest to the logarithm.

Hope this helps.

EDIT

Let's say that $t=\left\lfloor\log_2 n\right\rfloor$, that is, $t$ is the greatest integer less than or equal to $\log_2 n$, so we know $$2^t\leq n< 2^{t+1}$$

We want to set $m=t$ if $n\leq \frac32\cdot2^t$ that is, if $$\log_2 n<\log_2\frac32+t=t+.584963...$$

so you compute $\log_2 n$, and round down if the integer part is less than $.584963$, otherwise, round up.

If $n$ happens to be very close to $3\cdot2^m$ for some integer $m$, you may still have to compute $2^m$ and $2^{m+1}$ to be sure which to take, because of roundoff error in computing the logarithm.

Related Question