Skip to content

Python Numpy log

  • by

Python Numpy log() function calculates the natural logarithm of x, where x belongs to all the input array elements. This function returns an array that contains the natural logarithmic value of x, which belongs to all elements of the input array.

You need to import Numpy to use the Numpy log() function:

import numpy as np
np.log(x, /, out=None, *, where=True)
  • x: Array is a mandatory parameter representing the input array for calculating log values.
  • out: This optional parameter represents the location where the result must be stored.
  • where: This optional parameter, when set to True, the output array will be set to the result function.

Python Numpy log examples

A simple example code computes the natural logarithm of two numbers.

import numpy as np

# input array
arr = np.array([1, 2, 6])

res = np.log(arr)

print(res)

Output:

Python Numpy log

Using numpy log() to calculate the element-wise natural logarithm of a 2D array.

import numpy as np

# Two-dimensional input array
arr = np.arange(1, 9).reshape(4, 2)

res = np.log(arr)

print(res)

Output:

[[0. 0.69314718]
[1.09861229 1.38629436]
[1.60943791 1.79175947]
[1.94591015 2.07944154]]

matplotlib pyplot numpy array

import numpy as np
import matplotlib.pyplot as plt

arr = [2, 2.2, 2.4, 2.6, 2.8, 3]
result1 = np.log(arr)
result2 = np.log2(arr)
result3 = np.log10(arr)
plt.plot(arr, arr, color='blue', marker="*")
plt.plot(result1, arr, color='green', marker="o")
plt.plot(result2, arr, color='red', marker="*")
plt.plot(result3, arr, color='black', marker="*")
plt.show()

Output: a graph with four straight lines with different colors.

matplotlib pyplot numpy array

Comment if you have any doubts or suggestions on this Nympy log topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading