NumPy – Using log2() and log10() functions (4 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

Introduction

NumPy, a fundamental package for numerical computations in Python, offers a wide range of mathematical operations. Among these, logarithmic functions are essential for various scientific computing tasks. In this article, we’ll explore the use of log2() and log10() functions with practical examples. Logarithms are a critical part of the mathematical landscape, being the inverse operations of exponentiations. They are prevalently used in domains like computer science, engineering, and physics. Let’s dive in and understand how to utilize these functions in NumPy.

Understanding the Basics

Before jumping into the examples, let’s clarify what these functions do:

  • np.log2(x): Computes the base 2 logarithm of x.
  • np.log10(x): Computes the base 10 logarithm of x.

These functions can handle scalars, vectors, or matrices as inputs and apply the operation element-wise. Moreover, if the input contains negative numbers, NumPy will return NaNs, as logarithms of negative numbers are undefined in the real number system.

Example 1: Basic Usage of log2() and log10()

import numpy as np

# Define a numpy array
arr = np.array([1, 2, 4, 10, 100])

# Calculating log2
log2_results = np.log2(arr)
print('log2 results:', log2_results)

# Calculating log10
log10_results = np.log10(arr)
print('log10 results:', log10_results)

This example demonstrates the basic usage of both functions, calculating the logarithms of a simple array of numbers. The output emphasizes how each function maps the array elements to their respective logarithmic values in bases 2 and 10:

log2 results: [0.         1.         2.         3.32192809 6.64385619]
log10 results: [0.         0.30103    0.60205999 1.         2.        ]

Example 2: Working With Multi-Dimensional Arrays

import numpy as np

# Create a 2D array
matrix = np.array([[1, 2, 4], [10, 100, 1000]])

# Applying log2
log2_matrix = np.log2(matrix)
print('2D log2 results:\n', log2_matrix)

# Applying log10
log10_matrix = np.log10(matrix)
print('2D log10 results:\n', log10_matrix)

In this example, we extend our examination to two-dimensional arrays. Note how NumPy calculates logarithms for each element individually, maintaining the structure of the original array.

Output:

2D log2 results:
 [[0.         1.         2.        ]
 [3.32192809 6.64385619 9.96578428]]
2D log10 results:
 [[0.         0.30103    0.60205999]
 [1.         2.         3.        ]]

Example 3: Handling Complex Numbers

While logarithms of negative numbers are not defined in the real number system, complex numbers provide a way to circumvent this limitation. NumPy can calculate logarithms for complex numbers as follows:

import numpy as np

# Creating an array with complex numbers
complex_arr = np.array([1+2j, 3+4j, -1-1j])

# Using log2 and log10
log2_complex = np.log2(complex_arr)
print('Complex log2 results:\n', log2_complex)

log10_complex = np.log10(complex_arr)
print('Complex log10 results:\n', log10_complex)

Output:

Complex log2 results:
 [1.16096405+1.59727796j 2.32192809+1.33780421j 0.5       -3.39927011j]
Complex log10 results:
 [0.349485+0.48082858j 0.69897 +0.4027192j  0.150515-1.02328227j]

Notice how NumPy returns complex numbers as the output. This feature enables advanced mathematical computations involving complex numbers.

Example 4: Application in Scientific Data Analysis

Logarithms are widely used in scientific data analysis for data normalization, information theory, and more. Here’s an applied example:

import numpy as np
import matplotlib.pyplot as plt

# Simulating an exponential distribution
values = np.random.exponential(scale=2, size=1000)

# Using log2 to normalize
log_values = np.log2(values)

# Plotting results
plt.hist(values, bins=30, alpha=0.5, label='Original')
plt.hist(log_values, bins=30, alpha=0.5, label='Log2 Normalized')
plt.legend()
plt.show()

This example showcases how logarithmic transformations can be used to normalize distributions, making them easier to analyze and understand.

Conclusion

The log2() and log10() functions in NumPy are versatile tools for computing logarithms in base 2 and base 10, respectively. Through the examples provided, it is clear that these functions are essential for both basic mathematical operations and complex scientific computing tasks. Whether you’re working with simple arrays or analyzing scientific data, understanding how to utilize these logarithmic functions will greatly enhance your data analysis capabilities.