numpy.log() is a NumPy function used to compute the natural logarithm (base e) of each element in an input array or a single value. It works element-wise and returns a NumPy array containing the logarithmic results.
This example shows how numpy.log() calculates the natural logarithm of each value in a list of positive numbers.
import numpy as np
x = [1, 2, 4]
y = np.log(x)
print(y)
Output
[0. 0.69314718 1.38629436]
Explanation: np.log(x) computes the natural logarithm of every element in x.
Syntax
numpy.log(x)
- Parameters: x - Array like or scalar input containing positive values.
- Return: Returns an array (or scalar) with the natural logarithm of each element.
Examples
Example 1: This example calculates the natural logarithm of all elements in a one-dimensional NumPy array.
import numpy as np
a = np.array([1, 3, 9])
r = np.log(a)
print(r)
Output
[0. 1.09861229 2.19722458]
Explanation: np.log(a) applies the natural log to each element of a.
Example 2: This example verifies that log(exp(x)) = x using NumPy’s exponential values.
import numpy as np
v = np.exp([1, 2])
r = np.log(v)
print(r)
Output
[1. 2.]
Explanation: np.log(v) returns the original values because logarithm is the inverse of exponentiation.
Example 3: This example demonstrates how numpy.log() works on a two-dimensional array.
import numpy as np
m = np.array([[1, 2], [4, 8]])
r = np.log(m)
print(r)
Output
[[0. 0.69314718] [1.38629436 2.07944154]]
Explanation: np.log(m) computes the natural logarithm element-wise for the 2D array m.