w3resource

NumPy: Calculate exp(x) - 1 for all elements in a given array


Write a NumPy program to calculate exp(x) - 1 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.7182817  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.expm1(x): Here np.expm1(x) calculates e raised to the power of the input value x and then subtracts 1 from the result.

r2 = np.exp(x) – 1: Here np.exp(x) computes the exponential of x, which means it calculates e raised to the power of the input value x. Here, x is a NumPy array containing values 1.0, 2.0, 3.0, and 4.0, and the output of np.exp(x) is also a NumPy array, where each element of the array is e raised to the power of the corresponding element of x.

assert np.allclose(r1, r2): This code compares the results of np.expm1(x) and np.exp(x)-1 using the np.allclose() function. The np.allclose() function returns True if all elements of two arrays are equal within a certain tolerance.

Python-Numpy Code Editor: