NumPy Logarithms and Exponents
Logarithms reverse exponentiation for positive inputs in ordinary real arithmetic. Choose the log base and reject or handle values outside the intended domain.
How it works
np.log uses the natural base, while log2 and log10 use bases two and ten. log1p and expm1 are useful around zero because they avoid some precision loss from separately forming one plus a small value or subtracting one after exponentiation. This lesson uses values with simple known answers. An application should still decide how zero, negatives and overflow are reported rather than silently treating warnings as valid measurements.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python logs-exponents.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
values = np.array([1., 10., 100.])
print(np.log10(values).tolist())
print(np.isclose(np.expm1(np.log1p(0.001)), 0.001))
def positive_log(value):
values = np.asarray(value, dtype=np.float64)
if not np.isfinite(values).all() or (values <= 0).any():
raise ValueError("Expected finite positive inputs")
return np.log(values)
try:
positive_log(0.)
except ValueError:
print("Rejected zero logarithm")
Expected result
[0.0, 1.0, 2.0] True Rejected zero logarithm
The logarithms match the powers of ten and the small-value round trip is checked with a tolerance. The explicit domain guard rejects zero in both runtimes without relying on floating-point exception flags, whose browser behaviour differs. Real-valued logarithms do not make a negative input finite.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.