views:

136

answers:

7

How should I compute log to the base 2 in python. Eg. I have this equation where i am using log base 2 import math e = -(t/T)* math.log((t/T)[, 2])

+1  A: 

log_base_2(x) = log(x) / log(2)

Alexandre C.
+1  A: 

logbase2(x) = log(x)/log(2)

Conor
+2  A: 
>>> 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
>>> 
puzz
This is built in to the `math.log` function. See unutbu's answer.
tgray
You're right, didn't know that - thanks ;)
puzz
A: 

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)
Platinum Azure
+15  A: 

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
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
unutbu
+1. Change-of-base formula FTW
Matt Ball
`base` argument added in version 2.3, btw.
Joe Koberg
+1  A: 

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
Ugo
+2  A: 

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
Selinap