# logarithm – Log to the base 2 in python

## logarithm – Log to the base 2 in python

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

``````In : import math

In : 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 : math.log(8,2)
Out: 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
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                 # same result
``````
• Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.

• Python frexp() returns a tuple (mantissa, exponent). So `` 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
``````import math