w3resource

NumPy: Compute e^x, element-wise of a given array


31. Element-wise Exponential Function

Write a NumPy program to compute ex, element-wise of 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 exponential (e^x) for each element of the array x
print("\ne^x, element-wise of the said:")
r = np.exp(x)
print(r) 

Sample Output:

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

e^x, element-wise of the said:
[ 2.7182817  7.389056  20.085537  54.59815  ]

Explanation:

In the above code –

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

r = np.exp(x) – Here np.exp() function is applied to x, which returns a new array r containing the exponential value of each element in x. The exponential function raises the constant e to the power of each element in x, so the resulting array r will have the values [2.718282 , 7.389056 , 20.085537, 54.598152].


For more Practice: Solve these Related Problems:

  • Implement a function that computes the exponential of each element in an array using np.exp.
  • Test the function on arrays with both positive and negative values to verify the exponential behavior.
  • Create a solution that compares the output of np.exp with a Taylor series approximation for small inputs.
  • Apply the exponential function to a multi-dimensional array to ensure element-wise operation.

Go to:


PREV : Extended Difference with Prepend and Append
NEXT : Compute exp(x) - 1

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.