NumPy exp() in python

Share this article

In Python, numpy.exp() is a function in the NumPy library that calculates the exponential of all elements in an array. It returns e (Euler’s number, approximately 2.718) raised to the power of each element in the input.

Example

import numpy as np

# Single value
print(np.exp(1))  # 2.718 (which is e^1)

# Array of values
print(np.exp([0, 1, 2]))  # [1.         2.71828183 7.3890561]

What it does

numpy.exp() computes e raised to the power of each input element, whether it’s a single number, a list, or an array. This is particularly useful in fields like data science, finance, and machine learning, where exponential functions are commonly used.

  • Single value: Returns the exponential of a single number.
  • Array: Returns an array with the exponential of each element.

Examples

Example 1: Basic usage with a single number

import numpy as np

result = np.exp(3)
print(result)  # 20.085536923187668 (which is e^3)

When you input a single number, such as 3, numpy.exp() returns e raised to the power of that number, providing approximately 20.0855.

Example 2: Using 0 as input

import numpy as np

result = np.exp(0)
print(result)  # 1.0

If the input is 0, numpy.exp() returns 1 because e to the power of 0 is always 1. This applies universally to any base in exponential functions.

Example 3: Applying to an array

import numpy as np

array = np.array([1, 2, 3])
result = np.exp(array)
print(result)  # [ 2.71828183  7.3890561  20.08553692]

When passing an array, numpy.exp() calculates the exponential for each element in the array. This example returns an array with the exponential values of 1, 2, and 3.

Example 4: Using with negative numbers

import numpy as np

result = np.exp([-1, -2, -3])
print(result)  # [0.36787944 0.13533528 0.04978707]

If the input contains negative numbers, numpy.exp() returns values between 0 and 1, corresponding to 1/e raised to the power of each negative input. This can be helpful for modeling decay processes or probabilities in statistics.