We use np.exp() to find the exponential of numbers, which means raising the number e (about 2.718) to the power of those numbers. np.log() helps us find the natural logarithm, which is the reverse of the exponential.
0
0
np.exp() and np.log() in NumPy
Introduction
When you want to calculate growth like population or money growing exponentially.
When you need to reverse an exponential calculation to find the original number.
When working with probabilities and statistics that use logarithms.
When transforming data to make it easier to analyze or visualize.
Syntax
NumPy
np.exp(x) np.log(x)
x can be a single number or an array of numbers.
np.exp() calculates e raised to the power of x.
np.log() calculates the natural logarithm (base e) of x. The input x must be positive.
Examples
Calculate e to the power of 1, which equals e (~2.718).
NumPy
import numpy as np np.exp(1)
Calculate the natural log of e squared, which returns 2.
NumPy
import numpy as np np.log(np.exp(2))
Calculate the exponential for each element in the array.
NumPy
import numpy as np arr = np.array([0, 1, 2]) np.exp(arr)
Calculate the natural log for each element, returning [0, 1, 2].
NumPy
import numpy as np np.log(np.array([1, np.e, np.e**2]))
Sample Program
This program shows how np.exp() raises e to each number in the array, and then np.log() reverses it back to the original numbers.
NumPy
import numpy as np # Create an array of values values = np.array([0, 1, 2, 3]) # Calculate exponential of each value exp_values = np.exp(values) # Calculate natural log of the exponential values log_values = np.log(exp_values) print("Original values:", values) print("Exponential values:", exp_values) print("Log of exponential values:", log_values)
OutputSuccess
Important Notes
Input to np.log() must be positive; otherwise, it will return an error or NaN.
These functions work element-wise on arrays, so you can use them on lists of numbers easily.
Summary
np.exp() calculates e raised to the power of a number or array.
np.log() finds the natural logarithm, which is the inverse of the exponential.
They are useful for growth calculations, reversing exponentials, and data transformations.