• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:19 mins read
You are currently viewing How to Use NumPy log() in Python?

In Python, NumPy is a powerful library for numerical computing, including support for logarithmic operations. The numpy.log() function is used to compute the natural logarithm element-wise on a NumPy array. To compute the natural logarithm of x where x, such that all the elements of the given array. The natural logarithm log is the inverse of the numpy.exp(), so that log(exp(x))=x. The natural logarithm is log-in base e. Using the logspace() function you can get the uniformly spaced values on the log scale between the start and stop.

Advertisements

In this article, I will explain the NumPy log() function syntax and parameters and how you can get the log values of the given array.

1. Quick Examples of NumPy log() Function

Following are some quick examples of how to use the log() function in Python NumPy.


# Quick examples of numpy log() function

# Example 1: Get the log value of scalar
arr = np.array(2)
arr1 = np.log(arr)
 
# Example 2: Get the log values of a 1D array
arr = np.array([1, 4, 6])
log_values = np.log(arr)

# Example 3: Get the log values of 2-D array
arr = np.arange(1, 7).reshape(2,3)
log_values = np.log(arr)

# Example 4 : Get the log value of an array with base 2
arr = np.array([1, 4, 6])
log_values = np.log2(arr)

# Example 5: Get the log value of an array with base 10
arr = np.array([1, 4, 6])
log_values = np.log10(arr)

2. Syntax of NumPy log()

Following is the syntax of the log() function.


# Syntax of log()
numpy.log(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) =  

2.1 Parameters of log()

Following are the parameters of the log() function.

  • x – The input array. This is the array for which you want to compute the natural logarithm.
  • out (optional) – A location into which the result can be stored. If provided, it must have a shape that matches the expected output. If not provided or None, a freshly allocated array is returned.
  • where – Array and optional(This condition is broadcast over the input. At locations where the condition is set to True, the out array will be set to the function result. Elsewhere, the output array will retain its original value.
  • casting (optional) – Controls what kind of data casting may occur. Default is ‘same_kind’.
  • order (optional) – Controls the memory layout order of the result. Default is ‘K’
  • dtype (optional) – The desired data type for the output. If not specified, the data type of the input is used.
  • **kwargs : For other keyword-only arguments, see the ufunc docs.

2.2 Return Value of log()

It returns an array with a Natural logarithmic value of x, element-wise. It will return the scalar if x is the scalar.

  • If x is a real-valued data type, the return type will also be a real value. If a value cannot be written as a real value, then NaN is returned.
  • If x is a complex-valued input, the numpy.log() method has a branch cut [-inf,0], and it is continuous above it.

3. Usage of NumPy log()

Numpy is a package for working with numeric data in Python. As we know NumPy has many functions that are used for calculating mathematical operations of the data in an array. The numpy.log() is a mathematical function used to calculate the natural logarithm of x where x belongs to all the input array elements.

In the below example, the natural logarithm of 2 is approximately 0.69314718. The np.log() function computes the natural logarithm element-wise for each element in the input array. Since there’s only one element in the array in this case, it calculates the logarithm for that single element.


# Import numpy 
import numpy as np

# Create array
arr = np.array(2)
print("Original array:",arr)

# Get the log value of scalar
arr1 = np.log(arr)
print("Scalar log value:",arr1)

Yields below output.

NumPy log

4. Get the Log Values of 1-D NumPy Array

You can use the np.log() function to compute the natural logarithm of a 1-D NumPy array. For example, the np.log() function is applied element-wise to each element in the input array arr. The resulting log_values array contains the natural logarithm of each element in the original array.


# Create a 1-D NumPy array
arr = np.array([1, 4, 6])
print("Original array:\n", arr)

# Get the log values of a 1D array
log_values = np.log(arr)
print("Log values of the array:\n",log_values)

Yields below output.

NumPy log

These are the natural logarithm values corresponding to the elements in the original array [1, 4, 6].

5. Get the Log Values of 2-D NumPy Array

You can compute the natural logarithm of a 2-D NumPy array element-wise using the np.log() function. For instance, it creates a 2-D NumPy array using np.arange(1, 7).reshape(2,3), which generates numbers from 1 to 6 and reshapes them into a 2×3 array. Then, it computes the natural logarithm of each element in the 2-D array using np.log().


# Create a 2-D NumPy array
arr = np.arange(1, 7).reshape(2,3)
print("Original array:\n", arr)

# Get the log values of 2-D array
log_values = np.log(arr)
print("Log values of the 2D array:\n",log_values)

# Output:
# Original array:
#  [[1 2 3]
#  [4 5 6]]
# Log values of the 2D array:
#  [[0.         0.69314718 1.09861229]
#  [1.38629436 1.60943791 1.79175947]]

6. NumPy Logarithm with Base 2

You can calculate the log value of a NumPy array or a scalar with the base 2 using this function, It will return the array of log values with base2.

In the below example, it creates a NumPy array [1, 4, 6] and then computes the logarithms of the elements with base 2 using np.log2(). In this case, the logarithms of the elements [1, 4, 6] with base 2 are computed using the np.log2() function. The results are approximately 00, 22, and 2.58496252.5849625, respectively.


# Create array
arr = np.array([1, 4, 6])
print("Original array:\n", arr)

# Get the log value of an array with base 2
log_values = np.log2(arr)
print("Logarithms with base 2:\n",log_values)

# Output:
# Original array:
#  [1 4 6]
# Logarithms with base 2:
#  [0.        2.        2.5849625]

7. NumPy Logarithm with Base 10

To compute logarithms with base 10 in NumPy, you can use the np.log10() function. For instance,np.log10(arr) calculates the base 10 logarithms of the elements in the array. These are the logarithmic values of the elements in the original array with base 10, calculated using the np.log10() function.


# Create array
arr = np.array([1, 4, 6])
print("Original array:\n", arr)

# Get the log value of an array with base 10
log_values = np.log10(arr)
print("Logarithms with base 10:\n",log_values)

# Output:
# Original array:
#  [1 4 6]
# Logarithms with base 10:
#  [0.         0.60205999 0.77815125]

8. Get the log Value Using logspace()

NumPy logspace() function is used to create an array of evenly spaced values between two numbers on the logarithmic scale.

The below example creates an array of equally spaced numbers on the log scale between 2 and 3. It returns 50 values in the returned array. In linear space, the sequence starts at base ** start and ends with base ** stop.


import numpy as np

# Equally spaced values 
# On log scale between 2 and 3
arr = np.logspace(2, 3)
print("Equally spaced valueson log scale:\n",arr)

Yields below output. By default, it returns 50 values.


# Output:
Equally spaced valueson log scale:
[ 100.          104.81131342  109.8541142   115.13953993  120.67926406
  126.48552169  132.57113656  138.94954944  145.63484775  152.64179672
  159.98587196  167.68329368  175.75106249  184.20699693  193.06977289
  202.35896477  212.09508879  222.29964825  232.99518105  244.20530945
  255.95479227  268.26957953  281.1768698   294.70517026  308.88435965
  323.74575428  339.32217719  355.64803062  372.75937203  390.69399371
  409.49150624  429.19342601  449.8432669   471.48663635  494.17133613
  517.94746792  542.86754393  568.9866029   596.36233166  625.05519253
  655.12855686  686.648845    719.685673    754.31200634  790.60432109
  828.64277285  868.51137375  910.29817799  954.09547635 1000.        ]

9. Graphical representation of NumPy log

To get the graphical representation of numpy.log() use matplot library module. This module visualizes the even-spaced values.


import matplotlib.pyplot as plt
arr = np.array([5, 10, 15, 20])
arr1 = np.log(arr)
plt.plot(arr1, arr, marker='*', color='blue')

Yields below output

NumPy log

Frequently Asked Questions

What does numpy.log() do?

numpy.log() is a NumPy function used to compute the natural logarithm (base e) of the elements in a NumPy array. It operates element-wise, meaning it calculates the logarithm for each element individually.

How do I calculate the natural logarithm of a NumPy array

To calculate the natural logarithm (base e) of a NumPy array, you can use the numpy.log() function.

Can I calculate logarithms with a different base using NumPy?

You can calculate logarithms with a different base using the change of base formula. For instance, to compute logarithms with base 2, you can use np.log(x)/np.log(2) or directly use np.log2(x).

What happens if I apply numpy.log() to a negative number?

When you apply numpy.log() to a negative number, it will result in a complex number. Natural logarithms of negative real numbers are complex, so NumPy returns complex values for such inputs.

How do I calculate logarithms conditionally for specific elements in an array?

You can use the where parameter numpy.log() to calculate logarithm conditions

Can numpy.log() handle multi-dimensional arrays?

numpy.log() can handle multi-dimensional arrays. It operates element-wise, maintaining the shape of the input array.

How can I calculate logarithms in base 10 using NumPy?

You can calculate logarithms in base 10 using np.log10() function.

Conclusion

In this article, I have explained NumPy log() and using this how to get the natural logarithm values of all elements in a given array.

References