Python math.log2() 方法用于计算给定数字 x 的以 2 为底的对数。它计算必须提高到 2 才能获得 x 的幂。在数学上,该方法表示为 -
\log2\:(x)\:=\:\log_{2}({x})
换句话说,如果 log2(x) = y,则 2y = x。例如,如果 x = 8,则 math.log2(8) 返回 3,因为 23 = 8。
注意:要使用此功能,您需要导入 math 模块。
语法
以下是 Python math.log2() 方法的基本语法 -
math.log2(x)
参数
此方法接受整数或浮点数作为要计算以 2 为底的对数的参数。
返回值
该方法返回 x 的对数底数 2。返回值是一个浮点数。
示例 1
在下面的示例中,我们计算以 2 为基数的对数 8,这意味着将一个正整数作为参数传递给 log2() 方法 -
import math
result = math.log2(8)
print("The result obtained is:", result)
输出
获得的输出如下 -
The result obtained is: 3.0
示例 2
在这里,我们将一个小数值作为参数传递给 log2() 方法。我们计算以 2 为基数的对数为 0.5 -
import math
result = math.log2(0.5)
print("The result obtained is:", result)
输出
以下是上述代码的输出 -
The result obtained is: -1.0
示例 3
在此示例中,我们计算以 2 为基数的对数 3。由于 3 不是 2 的幂,因此结果是一个十进制值 -
import math
result = math.log2(3)
print("The result obtained is:", result)
输出
我们得到的输出如下所示 -
The result obtained is: 1.584962500721156
示例 4
现在,我们使用变量 “x” 来存储参数。然后我们计算以 2 为基数的对数 16 -
import math
x = 16
result = math.log2(x)
print("The result obtained is:", result)
输出
生成的结果如下所示 -
The result obtained is: 4.0