qp.math.ceil_log2

ceil_log2(n)[source]

Compute the ceiling of the base-2 logarithm of a number, with integer as output data type.

Parameters:

n (int or float) – Number to compute the rounded-up base-2 logarithm of. Traced inputs must have an integer data type.

Returns:

Rounded-up base-2 logarithm of n.

Return type:

int

Warning

Under just-in-time (JIT) compilation with JAX, this function will not raise an error for the input 0:

>>> import jax
>>> jax.jit(qp.math.ceil_log2)(0)
Array(-2147483648, dtype=int32)

Example

On powers of two, ceil_log2 simply acts like np.log2 whose result was converted to an int:

>>> qp.math.ceil_log2(8)
3

On other numbers, the rounding of the logarithm becomes visible:

>>> qp.math.log2(14)
3.807354922057604
>>> qp.math.ceil_log2(14)
4

Note that we always round up:

>>> qp.math.round(qp.math.log2(9))
3.0
>>> qp.math.ceil_log2(9)
4

The result is exact even for inputs with more significant bits than a float can hold:

>>> qp.math.ceil_log2(2**53 + 1)
54

For simple int inputs, this function computes the same as (n - 1).bit_length(), which does not work for inputs like np.int64.