math.log1p(x) returns the natural logarithm of 1 + x, staying accurate when x is close to 0.
When x is tiny (like 1e-16), evaluating 1 + x first rounds away x to 1.0, making math.log(1 + x) return 0.0. log1p(x) avoids forming 1 + x.
math.log1p() is a function in Python's standard math module: import it with import math and call math.log1p(...), or import the name directly with from math import log1p.
Syntax
Import math and pass an increment x > -1.
python
import math
val = math.log1p(x)
Call
What it does
math.log1p(0)
Returns 0.0.
math.log1p(1e-16)
Returns 1e-16 (where log(1 + 1e-16) returns 0.0).
math.log1p(math.e - 1)
Returns 1.0.
math.log1p(-1)
Raises ValueError: 1 + (-1) is zero.
Directly pairs with math.expm1() to convert cleanly between small relative increments and logarithmic scales.
Function signatures
python
math.log1p(x, /)
# returns: float ln(1 + x) for x > -1
Parameters
Parameter
Description
x
Required positional number strictly greater than -1.
Return Value
Return Value
Description
float
Natural log of 1 + x. Returns inf for inf and nan for nan.
Python Examples
Example 1 — Convert Tiny Financial Returns Into Log Returns
Compare math.log(1 + r) and math.log1p(r) across percent and sub-epsilon changes.
python
import math
for r in [0.01, 0.0001, 1e-16]:
naive = math.log(1.0 + r)
accurate = math.log1p(r)
print(f"r={r:.0e} naive={naive:.6e} log1p={accurate:.6e}")