Exponentials and Logarithms
Intuition
The exponential grows by the same factor for each step in ; the natural logarithm undoes it, answering "what power of gives ?". Logs turn multiplication into addition, which is why ML works with log-probabilities: multiplying hundreds of small probabilities underflows to 0, but adding their logs is perfectly stable.
Precise explanation
- ;
math.exp(x)is andmath.log(x)is (only for ). - Rules: , , , .
- Change of base: , e.g. .
- Compound growth: an amount growing by rate per step doubles after steps.
- Log-likelihood: .
- Log-sum-exp: . Computing overflows, so use with ; every exponent is then at most .
Worked example
Probabilities [1e-5] * 1000: the product is , which a float stores as 0.0, and
math.log(0.0) raises ValueError. The sum of logs is .
logsumexp([1000, 1000]) .
Common mistakes
math.log(x, 10)vsmath.log10(x)— both work;math.log(x)alone is base , not 10.- Taking the log of 0 or a negative number.
- Implementing log-sum-exp directly, which overflows for large inputs or underflows to
log(0)for very negative ones.
Why this matters
Cross-entropy loss, perplexity, Naive Bayes and softmax (DL-02) all rely on these identities, and MA-03 is built from .
Library implementation
The math module already provides math.log(x, base), math.log2, math.log10 and
math.log1p(r) (an accurate for small ). For log-sum-exp, SciPy offers
scipy.special.logsumexp, which uses the same max-subtraction trick (it also handles arrays and
weights). The tests below compare your functions with these when they are available; the SciPy
comparison is skipped if SciPy is not installed.
References
- Mathematics for Machine Learning — Marc Peter Deisenroth, A. Aldo Faisal, Cheng Soon Ong (Cambridge University Press) (
S009) - math — Mathematical functions — Python Software Foundation (
S050)