Python log

Python math.log 函数以 e 为底计算给定数字的对数值。log 函数的语法如下所示。

math.log(number, base);

base 参数是可选的。如果省略此参数,Python math.log 函数将默认 e 作为对数底。但是,您可以使用此参数更改它。

Number: 一个有效的数字表达式。

  • 如果 number 参数是正数,它将返回输出。
  • 如果 number 是负数或零,它将返回 ValueError。
  • 如果不是数字,它将返回 TypeError。

Python math.log 函数示例

log 函数以 e 为底计算给定数字的对数值。在这里,我们使用此方法查找不同数据类型的对数值。

import math

Tup = (1, 2, 3, -4 , 5) # Tuple Declaration
Lis = [-1, 2, -3.5, -4 , 5] # List Declaration

print('Logarithm value of Positive Number = %.2f' %math.log(1))
print('Logarithm value of Positive Decimal = %.2f' %math.log(2.5))

print('Logarithm value of Tuple Item = %.2f' %math.log(Tup[2]))
print('Logarithm value of List Item = %.2f' %math.log(Lis[4]))

print('Logarithm value of Multiple Number = %.2f' %math.log(2 + 7 - 5))
print('Logarithm value of String Number = ', math.log('Hello'))
Python LOG Function
  1. 在前两个语句中,我们直接在正整数和十进制值上使用了 math.log 函数。
  2. 接下来两个语句,我们在 Tuple 和 List 项上使用了 math 函数。如果您观察上面的 Python 屏幕截图,此 Math 函数在它们上面运行良好。
  3. 我们直接对多个值进行了尝试。
  4. 我们尝试将对数函数应用于字符串值,它返回 TypeError: a float is required。
  5. 接下来,我们尝试将其应用于负值,它返回 ValueError: math domain error。
  6. 最后,我们将其应用于零值。正如我们之前所说,它返回 ValueError: math domain error。