0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use exp in NumPy: Syntax, Examples, and Tips

Use numpy.exp() to calculate the exponential (e^x) of each element in a NumPy array or number. Pass a number, list, or array as input, and it returns an array with the exponential values.
๐Ÿ“

Syntax

The numpy.exp() function calculates the exponential of all elements in the input array or number. The syntax is simple:

  • numpy.exp(x): where x can be a single number, list, or NumPy array.
  • The function returns an array with the exponential of each element.
python
import numpy as np

result = np.exp(x)
๐Ÿ’ป

Example

This example shows how to use numpy.exp() on a single number and on a NumPy array. It calculates e to the power of each element.

python
import numpy as np

# Single number
single_value = 2
exp_single = np.exp(single_value)

# Array of numbers
array_values = np.array([0, 1, 2, 3])
exp_array = np.exp(array_values)

print(f"exp({single_value}) =", exp_single)
print("exp(array) =", exp_array)
Output
exp(2) = 7.38905609893065 exp(array) = [ 1. 2.71828183 7.3890561 20.08553692]
โš ๏ธ

Common Pitfalls

Common mistakes when using numpy.exp() include:

  • Passing a list without converting to a NumPy array (still works but less efficient).
  • Confusing np.exp() with the math module's exp() which only works on single numbers, not arrays.
  • Not importing NumPy before using np.exp().
python
import math
import numpy as np

# Wrong: math.exp on a list (raises error)
try:
    math.exp([1, 2, 3])
except TypeError as e:
    print("Error:", e)

# Right: numpy.exp on a list
print(np.exp([1, 2, 3]))
Output
Error: must be real number, not list [ 2.71828183 7.3890561 20.08553692]
๐Ÿ“Š

Quick Reference

FunctionDescription
numpy.exp(x)Returns e raised to the power of each element in x
Input xNumber, list, or NumPy array
OutputNumPy array with exponential values
Importimport numpy as np
Common errorUsing math.exp on arrays causes TypeError
โœ…

Key Takeaways

Use numpy.exp() to compute the exponential of numbers or arrays element-wise.
Input can be a number, list, or NumPy array; output is always a NumPy array.
Do not use math.exp for arrays; it only works with single numbers.
Always import NumPy before using np.exp().
numpy.exp() is efficient and works element-wise on arrays.