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): wherexcan 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'sexp()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
| Function | Description |
|---|---|
| numpy.exp(x) | Returns e raised to the power of each element in x |
| Input x | Number, list, or NumPy array |
| Output | NumPy array with exponential values |
| Import | import numpy as np |
| Common error | Using 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.