w3resource

NumPy: Calculate 2p for all elements in a given array


Write a NumPy program to calculate 2p for all elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array of float32 type
x = np.array([1., 2., 3., 4.], np.float32)

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

# Calculating exp(x) - 1 for each element of the array x
print("\nexp(x)-1 for all elements of the said array:")
r1 = np.expm1(x)
r2 = np.exp(x) - 1.

# Asserting whether the results from np.expm1 and np.exp - 1 are close
assert np.allclose(r1, r2)

# Printing the resulting array after exp(x) - 1 calculation
print(r1) 

Sample Output:

Original array: 
[1. 2. 3. 4.]

exp(x)-1 for all elements of the said array:
[ 1.7182819  6.389056  19.085537  53.59815  ]

Explanation:

In the above code –

x = np.array([1., 2., 3., 4.], np.float32): This line creates a one-dimensional NumPy array x of data type float32 is created with the values [1., 2., 3., 4.].

r1 = np.exp2(x): Here the np.exp2() function is called with the x array as the input. This calculates the exponential value of 2 raised to the power of each element in the input array. The result of np.exp2() is assigned to r1.

r2 = 2 ** x: This code approaches another way of raising 2 to the power of each element of the array x is to use the exponentiation operator ** with the base 2 and the x array.

assert np.allclose(r1, r2): Finally, the np.allclose() function is used to check if r1 and r2 are equal within a certain tolerance. The result shows that the values computed by np.exp2 and 2 ** x are the same for all elements within a certain tolerance.

Python-Numpy Code Editor: