在Python中求以2为底的对数

152

我该如何在Python中计算以2为底的对数。例如,我有一个方程式,在其中使用了以2为底的对数。

import math
e = -(t/T)* math.log((t/T)[, 2])

logbase2(x) = log(x)/log(2) - Conor
5
如果你在 math.log() 函数调用中去掉方括号中的 ", 2",你的代码应该能正常工作。你尝试过吗? - martineau
1
math.log(value, base) - Valentin H
2
关于澄清math.log(x[, base]):文档中的方括号通常表示可选参数。 - Wolf
10个回答

292

了解这一点很好:

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

但还需要知道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

7
顺便提一下,自2.3版本开始新增了base参数。 - Joe Koberg
11
这个“?”语法是什么?我找不到相关的参考资料。 - wap26
20
在上面的内容中,我正在使用IPython交互式解释器。它的一个特性(可通过?访问)是动态对象内省 - unutbu

104
取决于输入或输出是 int 还是 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

浮点数 → 浮点数 math.log2(x)

import math

log2 = math.log(x, 2.0)
log2 = math.log2(x)   # python 3.3 or later

浮点数 → 整数 math.frexp(x)

如果你只需要一个浮点数的以2为底的对数的整数部分,提取指数就非常高效:

log2int_slow = int(math.floor(math.log(x, 2.0)))    # these give the
log2int_fast = math.frexp(x)[1] - 1                 # same result

Python的frexp()调用C函数frexp(), 它只是获取和调整指数。 Python的frexp()返回一个元组(mantissa, exponent)。所以[1]获取指数部分。 对于2的整数幂,指数比您预期的多1。例如,32存储为0.5x2⁶。这解释了上面的-1。对于1/32也适用,它被存储为0.5x2⁻⁴。向负无穷大取整,因此通过这种方式计算log₂31为4而不是5。log₂(1/17)为-5而不是-4。

int → int x.bit_length()

如果输入和输出都是整数,这个本地整数方法可能非常高效:

log2int_faster = x.bit_length() - 1
  • - 1是因为2ⁿ需要n+1位。适用于非常大的整数,例如2**10000

  • 向负无穷方向取整,所以这种计算方式得出的log₂31是4而不是5。


1
有趣。所以你在那里减去1是因为尾数在[0.5,1.0]范围内吗?如果可以的话,我会给这个更多的赞。 - LarsH
1
完全正确@LarsH。32被存储为0.5x2⁶,因此如果您想要log₂32=5,则需要减去1。对于1/32也是如此,它被存储为0.5x2⁻⁴。 - Bob Stein

20
如果您使用的是Python 3.3或更高版本,则它已经内置了一个计算log2(x)的函数。
import math
'finds log base2 of x'
answer = math.log2(x)

如果你使用的是旧版本的Python,则可以这样做

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

11

使用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

额外加分算法可以适应于始终给出正确的整数部分,不像 int(math.log(x, 2))。 - user12861

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

这是math.log函数内置的。请参考unutbu的答案。 - tgray

2
尝试这个,
import math
print(math.log(8,2))  # math.log(number,base) 

2
在Python 3或更高版本中,math类具有以下函数。
import math

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

或者你可以一般地使用math.log(x, base),对于任何你想要的底数。


也许一个链接不会有坏处 https://docs.python.org/3/library/math.html#math.log1p - Wolf

0
不要忘记 log[base A] x = log[base B] x / log[base B] A
所以如果你只有 log(自然对数)和 log10(以10为底的对数),你可以使用。
myLog2Answer = log10(myInput) / log10(2)

0

使用 help 方法

>>> 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])

返回以给定底数为基数的x的对数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接