Log to the base 2 in python


How should I compute log to the base two in python. Eg. I have this equation where I am using log base 2

import math
e = -(t/T)* math.log((t/T)[, 2])
7/12/2012 2:10:26 PM

Accepted Answer

It's good to know that

alt text

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
    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
9/15/2010 4:23:24 PM

float → float math.log2(x)

import math

log2 = math.log(x, 2.0)
log2 = math.log2(x)   # python 3.4 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)))
log2int_fast = math.frexp(x)[1] - 1
  • 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 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 is 4 not 5. log₂(1/17) is -5 not -4.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow