Python math.log() 方法



Python 的 math.log() 方法用于计算正数值的自然对数(以 e 为底)。

对数的一般和简单的定义是指数的逆运算。这意味着,对数的结果是底数要提升到的幂。因此,此方法的结果始终是浮点数。

以 'e' 为底的对数可以表示如下

logba = p

其中,

  • a: 任何数字
  • b: 对数的底数
  • p: 底数提升到的幂

注意 - 此函数无法直接访问,因此我们需要导入 math 模块,然后需要使用 math 静态对象调用此函数。

语法

以下是 Python math.log() 方法的语法:

math.log( x )

参数

  • x - 这必须是正数值。

返回值

此方法返回 x 的自然对数,其中 x > 0。

示例

以下示例显示了 Python math.log() 方法的使用。我们在这里将正值作为参数传递给此方法,因此结果也将是正浮点数。

import math # This will import the math module

# Create a numeric object
x = 36.789

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

当我们运行上述程序时,它会产生以下结果:

The logarithm of x is: 3.6051988874479988

示例

但是,如果我们将负值作为参数传递给此方法,则会引发 ValueError,因为自然对数的定义域仅为正实数。

import math # This will import the math module

# Create a numeric object
x = -76.43

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

如果我们编译并运行上面的程序,则输出显示如下:

Traceback (most recent call last):
  File "main.py", line 7, in 
    ln = math.log(x)
ValueError: math domain error

示例

此方法也不接受数值以外的参数。

在以下示例中,让我们创建一个包含数值的列表并将其作为参数传递给此方法。由于列表是可迭代对象,因此预计会引发 ValueError。

import math # This will import the math module

# Create a list object
x = [12, 45.68, 112, 66.33]

# Calculate the natural logarithm of x
ln = math.log(x)

# Display the log value
print("The logarithm of x is:", ln)

如果我们执行上面的程序,则会引发以下 ValueError:

Traceback (most recent call last):
  File "main.py", line 7, in 
ln = math.log(x)
TypeError: must be real number, not list

示例

但是,我们可以使用循环语句迭代上面示例中给出的列表,并找到其中存在的数值的自然对数。

import math # This will import the math module

# Create a list object
x = [12, 45.68, 112, 66.33]

# Using a for loop, iterate through the list
for n in range(0, len(x)):
   # Calculate the natural logarithm of x
   ln = math.log(x[n])
   # Display the log value
   print("The logarithm of x[",n,"] is:", ln)

在编译并执行上述程序后,结果如下:

The logarithm of x[ 0 ] is: 2.4849066497880004
The logarithm of x[ 1 ] is: 3.821660565347755
The logarithm of x[ 2 ] is: 4.718498871295094
The logarithm of x[ 3 ] is: 4.194642283537465

示例

此 log() 方法与 exp() 方法完全相反。这意味着,log() 方法的参数是 exp() 方法的返回值。

在此示例中,我们正在创建一个对象 'x' 并将其作为参数传递给 exp() 方法。从此方法获得的返回值存储在另一个变量 'var' 中。现在,如果存储在 'var' 中的值作为参数传递给 log() 方法,则预期返回值将是存储在 'x' 中的值。

import math # This will import the math module

# Create a list object
x = 12.34

# Pass x as an argument to the exp() method
var = math.exp(x)

print("The exponent value of x is:", var)

# Calculate the natural logarithm of x
ln = math.log(var)

# Display the log value
print("The logarithm of x is:", ln)

上面程序的输出显示如下:

The exponent value of x is: 228661.9520568098
The logarithm of x is: 12.34
python_maths.htm
广告
© . All rights reserved.