1
$\begingroup$

Is there any simple formula that can be used to find the nearest power of 2 of a number?

So, let's say I got the number $15$, it has to give $16$, If I got the number $55$, it gives me $64$, etc.

$\endgroup$
6
  • 1
    $\begingroup$ Nearest in what sense? is $12$ "nearer" to $8$ or is it "nearer" to $16$? What about $11.5$? Whatever your final interpretation, play with $\log_2$ and floor/ceiling functions. $\endgroup$
    – JMoravitz
    Dec 5, 2019 at 14:56
  • $\begingroup$ indeed, if it is the same distance to two power of 2's, it can use any of the two. I was wondering if their is a closed form formula, without using floor/ceiling functions... $\endgroup$ Dec 5, 2019 at 14:57
  • 4
    $\begingroup$ Given the very nature of what you are describing as being a step function of sorts... a floor or ceiling is almost guaranteed in some form. $\endgroup$
    – JMoravitz
    Dec 5, 2019 at 14:58
  • 1
    $\begingroup$ If you convert you number into binary, you can easily do this $\endgroup$
    – Vasili
    Dec 5, 2019 at 14:59
  • 1
    $\begingroup$ @Steven31415 Not true. That would make $2^{n+1/2}$ the dividing line between $2^n$ and $2^{n+1}$, but it should be $3 \cdot 2^{n-1}$. $\endgroup$ Dec 5, 2019 at 15:09

2 Answers 2

1
$\begingroup$

Converting integer into binary can produce a simple Excel formula:
POWER(2,LEN(DEC2BIN(your cell)))

$\endgroup$
1
$\begingroup$

$a=\log_2 x- \lfloor \log_2 x \rfloor$

$b=\lceil \log_2 x \rceil -\log_2 x$

If $min\{a,b\}=a$ then the nearest power of $2$ is $2^{\lfloor \log_2 x \rfloor}$,

Else it is $2^{\lceil \log_2 x \rceil }$

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .