Com*_*er7 103 python logarithm
我应该如何在python中计算log 2的基数.例如.我有这个等式,我在使用log base 2
import math
e = -(t/T)* math.log((t/T)[, 2])
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 220
很高兴知道这一点

但也知道
math.log带有一个可选的第二个参数,允许你指定基数:
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
Run Code Online (Sandbox Code Playgroud)
Bob*_*ein 58
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.4 or later
Run Code Online (Sandbox Code Playgroud)
如果你需要的只是浮点数的log base 2的整数部分,math.log2(x)那么效率可能非常高:
log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
Run Code Online (Sandbox Code Playgroud)
Python frexp()调用C函数frexp(),它只是抓取并调整指数.
Python frexp()返回一个元组(尾数,指数).因此math.frexp(x)得到指数部分.对于2的整数幂,指数比你预期的多一个.例如,32存储为0.5x2⁶.这解释了[1]上述情况.也适用于1/32,存储为0.5×2 -6.
如果输入和输出都是整数,则整数方法- 1可能更有效:
log2int_faster = x.bit_length() - 1
Run Code Online (Sandbox Code Playgroud)
x.bit_length()因为2ⁿ需要n + 1位.这是适用于非常大的整数的唯一选项,例如- 1.
所有int输出版本都将日志置于负无穷大,因此log231为4而不是5.
aka*_*kar 15
如果您使用的是python 3.4或更高版本,那么它已经具有用于计算log2(x)的内置函数
import math
'finds log base2 of x'
answer = math.log2(x)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是旧版本的python,那么您可以这样做
import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)
Run Code Online (Sandbox Code Playgroud)
riz*_*iza 10
使用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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177130 次 |
| 最近记录: |