Python Glossary Русский

all Python 3Numbers & mathfunction

math.log1p

roots/powers

The natural logarithm ln(1 + x), accurate for small x.

Syntax

math.log1p(...)

For very small x the sum 1 + x rounds to 1.0 before the logarithm is even taken, so math.log(1 + x) collapses to zero; log1p computes ln(1+x) directly and keeps the significant digits. Reach for it whenever x is a small relative change — returns, probabilities, accumulating log-likelihoods. The domain is x > -1 (anything else raises ValueError), and math.expm1 is its inverse.

Examples

import math
print(math.log1p(0))   # → 0.0
print(math.log1p(1))   # → 0.6931471805599453
print(math.log(1 + 1e-16))   # → 0.0
print(math.log1p(1e-16))   # → 1e-16
print(math.log1p(-1))   # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy