NumPy log() In Python

Share this article

In Python, NumPy’s log() function computes the natural logarithm (base e) of each element in an array. It is part of the NumPy library and is used for performing logarithmic operations on numerical data in arrays.

Key Takeaway

numpy.log() calculates the natural logarithm (base e) for every element in an array. This function is useful in mathematical, scientific, and financial calculations where logarithmic transformations of data are needed.

Example

import numpy as np

arr = np.array([1, np.e, np.e**2])
print(np.log(arr))  

# Output: [0. 1. 2.]

What it does

In this example, np.log(arr) computes the natural logarithm of each element in the array. For 1, the log is 0; for e, it’s 1; and for , it’s 2.

  • Input: An array of numbers.
  • Output: A new array containing the natural logarithm of each input element.

Examples

Example 1: Logarithm of an array with positive numbers

arr = np.array([1, 10, 100, 1000])
print(np.log(arr))

# Output: [0.         2.30258509 4.60517019 6.90775528]

The np.log() function calculates the natural logarithm for each element. For 1, the log is 0. For 10, the log is approximately 2.302, and so on.

Example 2: Logarithm of an array with decimals

arr = np.array([0.5, 1.5, 2.5])
print(np.log(arr))

# Output: [-0.69314718  0.40546511  0.91629073]

Here, np.log() computes the logarithm for each decimal. The results include negative values since the natural logarithm of numbers between 0 and 1 is negative.

Example 3: Logarithm of a multi-dimensional array

arr = np.array([[1, np.e], [np.e**2, np.e**3]])
print(np.log(arr))

# Output:
# [[0. 1.]
#  [2. 3.]]

np.log() works with multi-dimensional arrays, applying the logarithm to each element. In this example, it correctly computes the logarithms for all elements in the 2D array.

Example 4: Handling zeros and negative numbers

arr = np.array([0, -1, 2])
print(np.log(arr))

# Output: [      -inf       nan 0.69314718]

If the array contains 0 or negative numbers, np.log() will return -inf (negative infinity) for 0 and nan (not a number) for negative values, indicating invalid inputs for the logarithm function.