NumPy: Compute natural, base 10, and base 2 logarithms for all elements in a given array
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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics