math.log(x) returns the natural logarithm (base e) of positive number x. With an optional second argument, math.log(x, base) computes the logarithm in that base as math.log(x) / math.log(base).
For base 2 or base 10, prefer math.log2() and math.log10(), which are computed directly and avoid rounding quirks like math.log(1000, 10) returning 2.9999999999999996.
math.log() is a function in Python's standard math module: import it with import math and call math.log(...), or import the name directly with from math import log.
Syntax
Pass one positive number for natural log, or add a positive base != 1.
python
import math
ln_val = math.log(x)
log_b = math.log(x, base)
Call
What it does
math.log(1)
Returns 0.0.
math.log(math.e)
Returns 1.0.
math.log(8, 2)
Returns 3.0.
math.log(0)
Raises ValueError: argument must be > 0.
Passing base=1 raises ZeroDivisionError because math.log(1) is 0.0.
Function signatures
python
math.log(x, [base=math.e])
# two-arg form divides log(x) by log(base)
Parameters
Parameter
Description
x
Required positive number (int or float). Zero or negative values raise ValueError.
base
Optional positive number not equal to 1. Defaults to math.e.
Return Value
Return Value
Description
float
Logarithm of x. Returns inf for inf and nan for nan.
Python Examples
Example 1 — Estimate Investment Doubling Time in Years
Compute continuous doubling time math.log(2) / rate across interest rates.
python
import math
for pct in [4, 6, 8, 12]:
rate = pct / 100.0
years = math.log(2) / rate
print(f"{pct:>2}% rate -> {years:.2f} years")
Output
4% rate -> 17.33 years
6% rate -> 11.55 years
8% rate -> 8.66 years
12% rate -> 5.78 years
How It Works
Continuous compounding rule. Solving e**(r*t) = 2 gives exact doubling time ln(2) / r.
Convert percentage. Dividing each integer percentage by 100.0 turns it into a decimal rate.
Formatted comparison. Two decimal places illustrate how doubling time drops faster than linearly as rates climb.
Example 2 — Use Custom Bases and Spot the log(1000, 10) Quirk
Evaluate logarithms in bases 2, 3, and 10, comparing math.log(1000, 10) against math.log10().