Python math.log2()方法

Python编程语言提供了一个库,math ,它包含各种数学运算的实现,如三角函数和对数函数。

对数指的是指数化的反函数。简单地说,一个数字的对数a ,就是另一个数字(x )的指数或数字(b ),为了使这个数字a ,应该提高到这个数字的基数。

Logarithm

在这篇文章中,我们将讨论math 模块中的一个方法,即log2() ,它可以计算一个以2 为底的数字的对数。

语法

math.log2(x)

参数

类型 说明
x 浮点数 一个非负的整数和非零的值。

返回

log2() 方法返回一个数字的以2 为底的对数。它等同于math.log(x, 2) ,在某些情况下,比它更精确。

例1:一个数字的基数-2对数

import math
print(math.log2(0.000001))
print(math.log2(1))
print(math.log2(0.341))
print(math.log2(99999))
print(math.log2(2352.579))

输出:

-19.931568569324174
0.0
-1.5521563556379145
16.609626047414267
11.200027454372368

上面的Python代码计算了0.000001,1,0.341,99999, 和2352.579 的以2为底的对数值。请注意,这些值都是非负数和非零值。

对于在(0, 1) 范围内的输入,基2对数返回负的结果。反之,范围[1, ∞) ,则会产生正的结果。

例2:如果输入的不是一个数字

import math
print(math.log2("this is a string"))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log2("this is a string"))
TypeError: must be real number, not str

上面的 Python 代码需要一个字符串作为输入。因为,log2() 方法期望的是一个数字,所以它引发了一个TypeError

例三:如果输入小于或等于0

import math
print(math.log2(0))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log2(0))
ValueError: math domain error

上面的Python代码把0 作为输入,由于0 是无效的输入,log2() 方法会产生一个ValueError

import math
print(math.log2(-9))

输出:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(math.log2(-9))
ValueError: math domain error

上面的Python代码把一个小于0 的值作为输入,而这样的值对于log2() 方法来说是无效的输入。因此,它引发了一个ValueError

例四:如果输入是无穷大

import math
print(math.log2(math.inf))

输出:

inf

当输入为无穷大时,结果也趋向于无穷大。这一点很容易从以2 为底的对数图中得到验证。

例 5: 如果输入是NaN

import math
print(math.log2(math.nan))

输出:

nan