带有Python示例的math.log()方法

Python math.log() 方法

math.log()方法数学模块的库方法,用于将给定数字的自然对数以e为底(默认情况下)。它接受数字和一个底数(可选),并返回自然对数。

注意:如果我们提供除数字以外的任何其他内容,该方法将返回TypeError – “ TypeError:需要浮点数”

它的语法 math.log() 方法:

    math.log(x [, base])

Parameter(s):

  • x –是要计算其对数的数字。

  • base –是一个可选参数,用于定义对数的任何特定底数。

返回值: float-它返回一个浮点值,它是数字x的自然或底数对数。

示例

    Input:
    x = 21

    # 函数调用
    print(math.log(x))

    Output:
    3.044522437723423

Python代码演示示例 math.log() 方法

# python代码演示示例 
# math.log() method

# 导入数学模块
import math

# log() with 1 parameter
x = 21
print("Natural logarithm of ", x, " is = ", math.log(x))

# log() with 2 parameters
x = 21
base = 5
print("logarithm of ", x, " with base ", base, " is = ", math.log(x, base))

输出结果

Natural logarithm of  21  is =  3.044522437723423
logarithm of  21  with base  5  is =  1.8916681496081529