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)
import math
x = 2.0
print(math.log(x)) # 0.6931471805599453
print(math.log(100, 10)) # 2.0 (log base 10 of 100)
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).
Join readers who trust AllThings.How
Add us as a preferred source on Google so our practical guides show up first next time you search.
Add to Google Preferences →Option 2 — Compute ln with NumPy (scalars, lists, ndarrays)
import numpy as np
arr = np.array([1, 2, 3, 4], dtype=float)
print(np.log(arr)) # [0. 0.69314718 1.09861229 1.38629436]
# 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]
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
import cmath
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
mathmodule doesn’t support complex inputs; usecmathor 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.






