numpy.log()
函数用于计算数组元素的自然对数。
示例
import numpy as np
# create a NumPy array
array1 = np.array([1, 2, 3, 4, 5])
# calculate the natural logarithm
# of each element in array1
result = np.log(array1)
print(result)
# Output: [0. 0.69314718 1.09861229 1.38629436 1.60943791]
log() 语法
numpy.log()
方法的语法是
numpy.log(array)
log() 参数
numpy.log()
方法接受一个参数
array
- 输入数组
log() 返回值
numpy.log()
方法返回一个数组,其中包含输入数组元素的自然对数值。
示例 1:使用 log() 计算自然对数
import numpy as np
# create a 2-D array
array1 = np.array([[0.5, 1.0, 2.0, 10.0],
[3.4, 1.5, 6.8, 4.12]])
# calculate the natural logarithm
# of each element in array1
result = np.log(array1)
print(result)
输出
[[-0.69314718 0. 0.69314718 2.30258509] [ 1.22377543 0.40546511 1.91692261 1.41585316]]
在这里,我们使用 np.log()
方法计算二维数组 array1 中每个元素的自然对数。
生成的数组 result 包含自然对数值。
示例 2:log() 的图形表示
为了提供对数函数的图形表示,让我们使用 Python 中流行的可视化库 matplotlib
来绘制对数曲线。
要使用 matplotlib
,我们首先将其导入为 plt
。
import numpy as np
import matplotlib.pyplot as plt
# generate x values from 0.1 to 5 with a step of 0.1
x = np.arange(0.1, 5, 0.1)
# compute the logarithmic values of x
y = np.log(x)
# plot the logarithmic curve
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('log(x)')
plt.title('Logarithmic Function')
plt.grid(True)
plt.show()
输出

在上面的示例中,我们使用 plt.plot(x, y)
将 x 数组绘制在 x 轴上,将包含自然对数值的 y 数组绘制在 y 轴上。