w3resource

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


32. Compute exp(x) - 1

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.


For more Practice: Solve these Related Problems:

  • Implement a function that uses np.expm1 to calculate exp(x) - 1 and compares the result with np.exp(x) - 1.
  • Test the function on an array with small values to verify numerical precision.
  • Create a solution that applies this computation element-wise on a 2D array and checks shape consistency.
  • Compare the performance of np.expm1 with a loop-based approach for computing exp(x) - 1.

Go to:


PREV : Element-wise Exponential Function
NEXT : Compute 2^p Element-wise

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.