np.log(x) is the inverse of np.exp(): it returns the exponent you'd need to raise e to in order to get x. Like np.sqrt(), it's only defined for non-negative real inputs when working with a real-valued array — log(0) produces -inf, and log of a negative number produces nan plus a RuntimeWarning, since the natural logarithm of a negative real number isn't a real number. NumPy also provides np.log2() and np.log10() for logarithms in other common bases, and np.log1p(x), which computes log(1 + x) with better numerical precision for x values very close to 0.
1Understanding np.log()
np.log(x) is the inverse of np.exp(): it returns the exponent you'd need to raise e to in order to get x. Like np.sqrt(), it's only defined for non-negative real inputs when working with a real-valued array — log(0) produces -inf, and log of a negative number produces nan plus a RuntimeWarning, since the natural logarithm of a negative real number isn't a real number. NumPy also provides np.log2() and np.log10() for logarithms in other common bases, and np.log1p(x), which computes log(1 + x) with better numerical precision for x values very close to 0.
Use np.log1p(x) instead of computing log(1 + x) manually when x is very close to 0 — computing 1 + x first can lose precision due to floating-point rounding, which np.log1p() avoids by handling that case specially.
import numpy as np
arr = np.array([1, np.e, np.e ** 2])
print(np.log(arr))2Practical Example
Here is a real-world application of np.log() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([1, 0, -1])
print(np.log(arr))3Best Practices
Follow these guidelines when working with np.log():
1. Guard against zero or negative inputs before calling np.log() if they're a realistic possibility, since they produce -inf or nan respectively
2. Use np.log1p() instead of computing log(1 + x) manually for values of x very close to zero, to avoid losing floating-point precision
3. Use np.log2()/np.log10() directly instead of dividing np.log(x) by np.log(2)/np.log(10), for both clarity and slightly better numerical precision
Tip: Use np.log1p(x) instead of computing log(1 + x) manually when x is very close to 0 — computing 1 + x first can lose precision due to floating-point rounding, which np.log1p() avoids by handling that case specially.
import numpy as np
arr = np.array([1, np.e, np.e ** 2])
print(np.log(arr))