Finding the exponent of $2$ such that $x \cdot 2^a$ is as close to $1$ as possible

55 Views Asked by At

How do I find an exponent of $2$ that when multiplied with another number would bring the result closest to the positive side $1$? Like this: $y = x \cdot 2^a$, where $y\ge 1$ has to be as small as possible, $x \in \mathbb R\setminus \{0\}$, and $a$ is the variable to determine.

This is for a program algorithm where I generate an infinitely zooming grid and x is the scale. Currently I just do this:

while (tScale > 1) {
    tScale /= 2;
}
while (tScale < 1) {
    tScale *= 2;
}

Since I was lazy at the time but I figured it must be rather inefficient and there's probably a more direct way to get the value.

1

There are 1 best solutions below

0
On

OP figured it out with the help of amWhy in comments:

var exp = Math.ceil(Math.log(1 / scale) / Math.log(2)); 
var tScale = Math.pow(2, exp) * scale; 

"Works great". The equivalent in math terms: $a = \lceil \ln(1 / x) / \ln(2)\rceil$.


That said, I'm pretty sure that the original code in the question is actually faster. Computing logarithms in double precision and then throwing out the fractional part does not look like an efficient thing to do.