= Doubling-loop ceiling logarithm
{title2=$i=\lceil\log_2 x\rceil$}
For an input $x\geq1$, start at $i=0,y=1$ and repeatedly increment $i$ and double $y$ while $y<x$. In exact arithmetic, the <loop invariant> $y=2^i$ and the minimality of the terminating index give $i=\lceil\log_2x\rceil$. For a general positive real input, the formula is instead $i=\max(0,\lceil\log_2x\rceil)$: if $0<x<1$, the loop makes no updates and cannot return a negative index.
Finite-width <integer arithmetic> also requires an overflow check. In wrapping signed 32-bit arithmetic, doubling $2^{30}$ produces the negative value $-2^{31}$ and a further doubling produces zero. For a positive input exceeding $2^{30}$, the loop can then remain at zero indefinitely. This is a <two's complement> wraparound example, not a universal language rule for signed overflow. A signed 64-bit doubling variable can represent the first power of two above every positive signed 32-bit input, repairing this particular range. The proof of the mathematical loop and the representation limits are separate parts of its correctness argument.
Back to article page