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])
In python 3 or above, math class has the fallowing 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.
log_base_2(x) = log(x) / log(2)
Try this ,
import math
print(math.log(8,2)) # math.log(number,base)
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)
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.3 or later
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 computed this way is 4 not 5. log₂(1/17) is -5 not -4.
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.