在Python中以2为底的对数

153 投票
10 回答
318902 浏览
提问于 2025-04-16 04:11

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

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

10 个回答

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

这要看输入和输出是整数(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()返回一个元组(尾数,指数)。所以用[1]可以获取指数部分。

  • 对于2的整数次方,指数比你想象的要多1。例如,32被存储为0.5x2⁶。这就是上面提到的- 1的原因。对于1/32也是如此,它被存储为0.5x2⁻⁴。

  • 向负无穷大取整,所以用这种方法计算log₂31的结果是4而不是5。log₂(1/17)的结果是-5而不是-4。


整数转整数 x.bit_length()

如果输入和输出都是整数,这个原生的整数方法会非常高效:

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

  • 向负无穷大取整,所以用这种方法计算log₂31的结果是4而不是5。

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

撰写回答