logarithm – Log to the base 2 in python

logarithm – Log to the base 2 in python

Its good to know that

log_b(a)

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

In [22]: import math

In [23]: math.log?
Type:       builtin_function_or_method
Base Class: <type builtin_function_or_method>
String Form:    <built-in function log>
Namespace:  Interactive
Docstring:
    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

Depends on whether the input or output is int or float.

assert 5.392317422778761 ==   math.log2(42.0)
assert 5.392317422778761 ==    math.log(42.0, 2.0)
assert 5                 ==  math.frexp(42.0)[1] - 1
assert 5                 ==            (42).bit_length() - 1

float → float math.log2(x)

import math

log2 = 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 the
log2int_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.5×2⁶. This explains the - 1 above. Also works for 1/32 which is stored as 0.5×2⁻⁴.
  • 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.

logarithm – Log to the base 2 in python

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)

Leave a Reply

Your email address will not be published. Required fields are marked *