152

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])
4
  • logbase2(x) = log(x)/log(2)
    – Conor
    Sep 15, 2010 at 16:17
  • 5
    What you have should work if you take the square brackets out around the ", 2" in the math.log() call. Have you tried it?
    – martineau
    Sep 15, 2010 at 18:44
  • 1
    math.log(value, base)
    – Valentin H
    Jan 7, 2015 at 22:10
  • 2
    As to clarify math.log(x[, base]): Square brackets in documentation often indicate optional arguments.
    – Wolf
    Jan 13, 2021 at 12:25

10 Answers 10

292

It's good to know that

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

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
3
  • 7
    base argument added in version 2.3, btw.
    – Joe Koberg
    Sep 15, 2010 at 18:09
  • 11
    What is this '?' syntax ? I can't find reference for it.
    – wap26
    Apr 30, 2013 at 13:59
  • 20
    @wap26: Above, I'm using the IPython interactive interpreter. One of its features (accessed with the ?) is dynamic object introspection.
    – unutbu
    Apr 30, 2013 at 17:51
104

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.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.

2
  • 1
    Interesting. So you're subtracting 1 there because the mantissa is in the range [0.5, 1.0)? I would give this one a few more upvotes if I could.
    – LarsH
    Feb 23, 2015 at 11:49
  • 1
    Exactly right @LarsH. 32 is stored as 0.5x2⁶ so if you want log₂32=5 you need to subtract 1. Also true for 1/32 which is stored as 0.5x2⁻⁴.
    – Bob Stein
    Feb 23, 2015 at 14:10
20

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)
0
11

Using numpy:

In [1]: import numpy as np

In [2]: np.log2?
Type:           function
Base Class:     <type 'function'>
String Form:    <function log2 at 0x03049030>
Namespace:      Interactive
File:           c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition:     np.log2(x, y=None)
Docstring:
    Return the base 2 logarithm of the input array, element-wise.

Parameters
----------
x : array_like
  Input array.
y : array_like
  Optional output array with the same shape as `x`.

Returns
-------
y : ndarray
  The logarithm to the base 2 of `x` element-wise.
  NaNs are returned where `x` is negative.

See Also
--------
log, log1p, log10

Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN,   1.,   2.])

In [3]: np.log2(8)
Out[3]: 3.0
7

http://en.wikipedia.org/wiki/Binary_logarithm

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res
1
  • Extra points for an algorithm that can be adapted to always give the correct integer part, unlike int(math.log(x, 2))
    – user12861
    Jan 10, 2012 at 13:43
6
>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 
1
  • This is built in to the math.log function. See unutbu's answer.
    – tgray
    Sep 15, 2010 at 16:26
2

Try this ,

import math
print(math.log(8,2))  # math.log(number,base) 
2

In python 3 or above, math class has the following functions

import math

math.log2(x)
math.log10(x)
math.log1p(x)

or you can generally use math.log(x, base) for any base you want.

1
0

Don't forget that log[base A] x = log[base B] x / log[base B] A.

So if you only have log (for natural log) and log10 (for base-10 log), you can use

myLog2Answer = log10(myInput) / log10(2)
0

Use help method

>>> import math
>>> help(math.log)

Help on built-in function log in module math:

log(...)
    log(x, [base=math.e])
    Return the logarithm of x to the given base.
    
    If the base not specified, returns the natural logarithm (base e) of x.
(END)

log(x, [base=math.e])

Return the logarithm of x to the given base.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.