Log to the base 2 in python Log to the base 2 in python python python

Log to the base 2 in python


It's good to know that

log_b(a) = log(a)/log(b)

but also know thatmath.log takes an optional second argument which allows you to specify the base:

In [22]: import mathIn [23]: math.log?Type:       builtin_function_or_methodBase Class: <type 'builtin_function_or_method'>String Form:    <built-in function log>Namespace:  InteractiveDocstring:    log(x[, base]) -> the logarithm of x to the given base.    If the base not specified, returns the natural logarithm (base e) of x.In [25]: math.log(8,2)Out[25]: 3.0


float → float math.log2(x)

import mathlog2 = math.log(x, 2.0)log2 = math.log2(x)   # python 3.3 or later

float → int math.frexp(x)

If all you need is the integer part of log base 2 of a floating point number, extracting the exponent is pretty efficient:

log2int_slow = int(math.floor(math.log(x, 2.0)))    # these give thelog2int_fast = math.frexp(x)[1] - 1                 # same result
  • Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.

  • Python frexp() returns a tuple (mantissa, exponent). So [1] gets the exponent part.

  • For integral powers of 2 the exponent is one more than you might expect. For example 32 is stored as 0.5x2⁶. This explains the - 1 above. Also works for 1/32 which is stored as 0.5x2⁻⁴.

  • Floors toward negative infinity, so log₂31 computed this way is 4 not 5. log₂(1/17) is -5 not -4.


int → int x.bit_length()

If both input and output are integers, this native integer method could be very efficient:

log2int_faster = x.bit_length() - 1
  • - 1 because 2ⁿ requires n+1 bits. Works for very large integers, e.g. 2**10000.

  • Floors toward negative infinity, so log₂31 computed this way is 4 not 5.


If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math'finds log base2 of x'answer = math.log2(x)

If you are on older version of python then you can do like this

import math'finds log base2 of x'answer = math.log(x)/math.log(2)