w3resource

NumPy: Compute natural, base 10, and base 2 logarithms for all elements in a given array


34. Compute Logarithms (Natural, Base 10, Base 2)

Write a NumPy program to compute natural, base 10, and base 2 logarithms for all elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array consisting of 1, e, and e^2
x = np.array([1, np.e, np.e**2])

# Displaying the original array
print("Original array: ")
print(x)

# Calculating natural logarithm (base e) of the array elements
print("\nNatural log =", np.log(x))

# Calculating common logarithm (base 10) of the array elements
print("Common log =", np.log10(x))

# Calculating base 2 logarithm of the array elements
print("Base 2 log =", np.log2(x)) 

Sample Output:

Original array: 
[1.         2.71828183 7.3890561 ]

Natural log = [0. 1. 2.]
Common log = [0.         0.43429448 0.86858896]
Base 2 log = [0.         1.44269504 2.88539008]

Explanation:

in the above code –

x = np.array([1, np.e, np.e**2]): This line creates a NumPy array x with 3 elements, where the first element is 1, the second element is the mathematical constant e (approximately equal to 2.71828), and the third element is e raised to the power of 2.

np.log(x): np.log(x) computes the natural logarithm (base e) of each element in the array x.

np.log10(x): np.log10(x) computes the common logarithm (base 10) of each element in the array x.

np.log2(x): np.log2(x) computes the base 2 logarithm of each element in the array x.


For more Practice: Solve these Related Problems:

  • Implement a function that computes np.log, np.log10, and np.log2 for a given array of positive numbers.
  • Test the function on a multi-dimensional array and verify that the logarithms are computed element-wise.
  • Create a solution that returns a dictionary with keys for natural, common, and base 2 logs.
  • Compare the computed logarithms with manually calculated values for a set of test numbers.

Go to:


PREV : Compute 2^p Element-wise
NEXT : Compute log1p (Natural Logarithm of 1 + x)

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.