The math.log(x[, base]) function computes the logarithm of x to the given base. If the base argument is omitted, it defaults to Euler's number e (≈ 2.71828), calculating the natural logarithm ($\ln(x)$).
Exponential Inverse: The natural logarithm is the exact mathematical inverse of math.exp() (math.log(math.exp(x)) == x).
The math.log() function is part of the standard math module:
import math
result = math.log(x[, base])
| Parameter | Type | Required? | Description |
|---|---|---|---|
x |
float or int |
Yes | The numeric value whose logarithm is to be computed. Must be strictly greater than zero (x > 0). |
base |
float or int |
No | Optional logarithmic base. Defaults to math.e (natural logarithm). Must be strictly positive and not equal to 1. |
Return Value: Returns a float representing the exponent to which base must be raised to produce x.
When called with a single argument, math.log() evaluates the natural logarithm ($\ln(x)$):
import math
print("ln(1):", math.log(1)) # 0.0 (any number to power 0 is 1)
print("ln(e):", math.log(math.e)) # 1.0
print("ln(2):", math.log(2)) # 0.6931471805599453
print("ln(10):", math.log(10)) # 2.302585092994046
ln(1): 0.0
ln(e): 1.0
ln(2): 0.6931471805599453
ln(10): 2.302585092994046
To evaluate a logarithm with any other base (e.g. base 2, base 5, base 10), pass the base as the second argument:
import math
print("log2(8): ", math.log(8, 2)) # 2^3 = 8 -> Output: 3.0
print("log10(100):", math.log(100, 10)) # 10^2 = 100 -> Output: 2.0
print("log5(625): ", math.log(625, 5)) # 5^4 = 625 -> Output: 4.0
Under the Hood: math.log(x, base) is calculated internally as math.log(x) / math.log(base), following the standard mathematical change-of-base formula.
Because the change-of-base division can introduce tiny rounding imprecisions, Python provides specialized, hardware-accelerated functions:
| Function | Base | Formula | Why Use Over math.log()? |
|---|---|---|---|
math.log2(x) |
2 | $\log_2(x)$ | More accurate than math.log(x, 2); essential for information theory, bit depth, and algorithmic complexity. |
math.log10(x) |
10 | $\log_{10}(x)$ | More accurate than math.log(x, 10); essential for scientific notation, decibel scales, and the Richter scale. |
math.log1p(x) |
e | $\ln(1 + x)$ | Accurate when $x$ is close to zero; avoids catastrophic cancellation errors in floating-point calculations. |
import math
# Specialized functions vs generic math.log
print(math.log2(1024)) # 10.0
print(math.log10(10000)) # 4.0
Logarithms are only mathematically defined for strictly positive real numbers ($x > 0$). If you pass zero or a negative number to math.log(), Python raises a ValueError: math domain error:
import math
try:
math.log(-10)
except ValueError as err:
print("Negative argument error:", err)
try:
math.log(0)
except ValueError as err:
print("Zero argument error: ", err)
Negative argument error: math domain error
Zero argument error: math domain error
Defensive Programming: Always validate that input numbers are positive (e.g. if x > 0:) before computing logarithms in production data pipelines.
In financial mathematics, the exact number of years required for an investment compounding annually at rate $r$ to double is given by the logarithmic formula:
$$t = rac{\ln(2)}{\ln(1 + r)}$$
Let's build an investment calculator using math.log() verified with unit assertions:
import math
def calculate_doubling_time(annual_rate_percent):
if annual_rate_percent <= 0:
raise ValueError("Growth rate must be strictly positive.")
r = annual_rate_percent / 100.0
# Exact formula: ln(2) / ln(1 + r)
return math.log(2) / math.log(1 + r)
# 7% annual growth doubles in approx 10.24 years (Rule of 72 estimates 72/7 = 10.28)
years_7 = calculate_doubling_time(7)
years_10 = calculate_doubling_time(10)
years_12 = calculate_doubling_time(12)
# Unit Assertions
assert round(years_7, 2) == 10.24
assert round(years_10, 2) == 7.27
assert round(years_12, 2) == 6.12
print("7% Annual Doubling Time:", round(years_7, 2), "years")
print("10% Annual Doubling Time:", round(years_10, 2), "years")
print("All doubling time assertions passed successfully!")
Open in Google Colab View on GitHub
Run all math.log() examples interactively, contrast custom base results with specialized log2/log10 functions, and verify the investment calculator with unit assertions directly in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
05-02-2023 | |
| X,Y on the same axis overlapping; however each carries its own width and length | |