Python log2 数学函数用于计算给定以 2 为底的数的对数值。在本节中,我们将通过一个示例讨论如何在该编程语言中使用 math log2 函数。
Python 编程语言中 log2 函数的语法如下所示。
math.log2(number);
- 如果数字参数是正数,函数将返回输出。
- 如果数字参数是负数或零,则返回 ValueError。
- 如果它不是数字,则返回 TypeError。
Python log2 函数示例
log2 函数用于计算给定以 2 为底的数的对数值。在本例中,我们将使用不同的数据类型检查以 2 为底的对数值并显示输出。
提示:math log2 函数比 math.log(x, 2) 更准确。请参阅对数文章以了解 log 函数。
import math
Tup = (10, 20, 30, -40 , 50) # Tuple Declaration
Lis = [-1, 2, 3.5, -43 , 50] # List Declaration
print('Logarithm value of Positive Number = %.2f' %math.log2(5))
print('Logarithm value of Positive Decimal = %.2f' %math.log2(2.5))
print('Logarithm value of Tuple Item = %.2f' %math.log2(Tup[2]))
print('Logarithm value of List Item = %.2f' %math.log2(Lis[2]))
print('Logarithm value of Multiple Number = %.2f' %math.log2(2 + 7 - 5))
print('Logarithm value of String Value = ', math.log2('Python'))

- 在前两个语句中,我们直接将其用于正整数和十进制值。
- 接下来的两个语句,我们将 log2 函数用于元组和列表项。如果您观察到上面的Python 屏幕截图,这个数学函数正在计算以 2 为底的对数值。
- 下一条语句,我们尝试了具有多个值的 Python log2 函数
- 接下来,我们尝试了字符串值,它返回 TypeError: a float is required
- 在这里,我们尝试了零值。正如我们之前所说,这返回了 ValueError: math domain error。
- 最后,我们尝试了负值。正如我们之前所说,它返回了 ValueError: math domain error。