Use math.log
to compute the natural logarithm (base e) of numbers in standard Python code, and switch to numpy.log
when you want fast, vectorized operations over arrays. Both return ln by default; NumPy additionally accepts array-like inputs and complex values.
Method 1 — Compute ln with the math module (scalars)
Step 1: Import the math module.
import math
Step 2: Calculate the natural log of a positive number using math.log(x)
.
x = 2.0
print(math.log(x)) # 0.6931471805599453
Step 3: Provide a second argument to compute a logarithm in another base when needed.
print(math.log(100, 10)) # 2.0 (log base 10 of 100)
Step 4: Guard against non‑positive inputs, which raise ValueError
.
def safe_ln(v: float) -> float:
if v <= 0:
raise ValueError("ln is undefined for non-positive values.")
return math.log(v)
print(safe_ln(1.0)) # 0.0
Tip: For values very close to zero, math.log1p(x)
gives better precision for ln(1+x).
Option 2 — Compute ln with NumPy (scalars, lists, ndarrays)
Step 1: Import NumPy.
import numpy as np
Step 2: Apply np.log
to a scalar, list, or NumPy array.
arr = np.array([1, 2, 3, 4], dtype=float)
print(np.log(arr)) # [0. 0.69314718 1.09861229 1.38629436]
Step 3: Handle zeros and negatives explicitly to avoid invalid results.
# Configure how NumPy reports floating errors (optional).
np.seterr(divide="ignore", invalid="ignore")
data = np.array([1.0, 0.0, -2.0, 3.0])
logs = np.log(data) # [-0. -inf nan 1.09861229]
# Mask out invalids for downstream use.
valid_mask = data > 0
logs_clean = np.full_like(data, np.nan)
logs_clean[valid_mask] = np.log(data[valid_mask])
print(logs_clean) # [0. nan nan 1.09861229]
Step 4: Compute other bases with the change‑of‑base formula when needed.
x = np.array([10, 100, 1000], dtype=float)
base = 10.0
print(np.log(x) / np.log(base)) # [1. 2. 3.]
- NumPy vectorizes the operation so large arrays compute quickly.
- For small x near zero,
np.log1p(x)
improves numerical accuracy for ln(1+x).
Approach 3 — Work with complex numbers
Step 1: Import the complex‑number math library for scalar complex values.
import cmath
Step 2: Use cmath.log
for complex scalars or np.log
for complex arrays.
z = 3 + 2j
print(cmath.log(z)) # (1.2824746787307684+0.5880026035475675j)
z_arr = np.array([1+1j, 2+0j, -1+0j], dtype=complex)
print(np.log(z_arr)) # Complex-valued natural logs
- The real-valued
math
module doesn’t support complex inputs; usecmath
or NumPy complex arrays.
That’s it—use math.log
for straightforward scalar ln and np.log
when you want vectorized array operations or complex numbers, and remember to guard non‑positive inputs in real-number workflows.
Member discussion