BRAGA

02 Writing02-02 Notes02-02-096

Natural Log Cancellation

Published 16 Apr 202611 min read
Contents
  1. 01Deep Breakdown
  2. 02Flowchart
  3. 03Real-world use
  4. 04The formula, piece by piece
  5. 05The formula in words
  6. 06Critical Concepts
  7. 07Step-by-step calculation (tiny example)
  8. 08Code examples
eln⁡x=xe^{\ln x} = x
(1)

Deep Breakdown

What it tells me (Situation Awareness): This is the natural-base specialization of the cancellation identity: eln⁡x=xe^{\ln x} = x for x>0x > 0, and its symmetric counterpart ln⁡(ex)=x\ln(e^x) = x for all real xx. These two statements say that e(⋅)e^{(\cdot)} and ln⁡(⋅)\ln(\cdot) are exact inverses of each other. In the context of DA/DS and ML, the natural log ln⁡\ln is the default logarithm because ee is the base of the exponential distribution, the Gaussian, and exponential family distributions generally. The identity eln⁡x=xe^{\ln x} = x is used constantly in: (1) simplifying expressions in log-likelihood functions for normal and exponential distributions; (2) the softmax function softmax(zi)=ezi/∑jezj\text{softmax}(z_i) = e^{z_i}/\sum_j e^{z_j} and its numerically stable form involving ln⁡\ln; (3) the parameterization of strictly positive quantities (e.g., σ=eln⁡σ\sigma = e^{\ln \sigma} so optimizing over ln⁡σ\ln \sigma avoids the σ>0\sigma > 0 constraint); (4) the exponential distribution survival function S(t)=e−λt=etln⁡e−λ=e−λtS(t) = e^{-\lambda t} = e^{t \ln e^{-\lambda}} = e^{-\lambda t} (circular but useful for manipulation); and (5) computing gradients of log-normal and Poisson likelihoods. The key operational difference from the general cancellation: eln⁡x=xe^{\ln x} = x requires x>0x > 0 (since ln⁡x\ln x is undefined for x≤0x \le 0), while ln⁡(ex)=x\ln(e^x) = x works for all real xx (since ex>0e^x > 0 always, so the argument to ln⁡\ln is always valid).

Flowchart

Natural logcancellation:e^(ln x) = xDirection 1: e^(lnx) = x —requires x 0Direction 2:ln(e^x) = x — allreal x validx 0 constraint:ln(x) definedonly for positivexe^x 0 always, soln argument isalways validML:re-parameterizeσ 0 as σ =e^(log_σ) —unconstrainedoptimizationML: ln(e^(Xβ)) =Xβ — Poissonregressionlog-linkNumerics:log-softmax =z_i - ln(sum_je^(z_j)) usesthis identityGeometric: y =e^x and y = ln xare reflectionsacross y = xTRAP: e^(log_2x) ≠ x — basesmust both be e;mismatchedbase breakscancellation

Real-world use

Where it is used

Softmax and log-softmax: in classification, the numerically stable log-softmax is LSM(z)i=zi−ln⁡ ⁣(∑jezj)\text{LSM}(z)_i = z_i - \ln\!\bigl(\sum_j e^{z_j}\bigr). To recover probabilities from log-softmax values: exp⁡(LSM(z)i)=ezi−ln⁡(∑jezj)=ezi/∑jezj\exp(\text{LSM}(z)_i) = e^{z_i - \ln(\sum_j e^{z_j})} = e^{z_i} / \sum_j e^{z_j} — directly applying ex−c=ex/ece^{x - c} = e^x / e^c and eln⁡(⋅)=(⋅)e^{\ln(\cdot)} = (\cdot). Unconstrained optimization of positive parameters: instead of constraining σ>0\sigma > 0, re-parameterize as σ=eα\sigma = e^\alpha and optimize over α∈R\alpha \in \mathbb{R}. At the optimum, σ^=eα^\hat{\sigma} = e^{\hat{\alpha}}, using eln⁡x=xe^{\ln x} = x in reverse.

Problem it solves

Expressions involving ef(x)e^{f(x)} inside a logarithm (or vice versa) look complex until the identity removes the composed function entirely. For example: the log-likelihood of the exponential distribution is ln⁡f(t;λ)=ln⁡(λe−λt)=ln⁡λ+ln⁡(e−λt)=ln⁡λ−λt\ln f(t; \lambda) = \ln(\lambda e^{-\lambda t}) = \ln \lambda + \ln(e^{-\lambda t}) = \ln \lambda - \lambda t — the second step uses ln⁡(e−λt)=−λt\ln(e^{-\lambda t}) = -\lambda t directly.

How it solves the problem

From the definition: ln⁡x=y  ⟺  ey=x\ln x = y \iff e^y = x. Substituting y=ln⁡xy = \ln x into eye^y gives eln⁡x=xe^{\ln x} = x by definition. The symmetric direction: ln⁡(ex)\ln(e^x) — since ln⁡\ln is the inverse of e(⋅)e^{(\cdot)}, applying ln⁡\ln to exe^x recovers the exponent xx. Both are just the statement that inverse functions composed in either order return the identity.

Example in a business

A data scientist is implementing a Poisson regression model. The model is ln⁡(μi)=xiTβ\ln(\mu_i) = \mathbf{x}_i^T\boldsymbol{\beta}, or equivalently μi=exiTβ\mu_i = e^{\mathbf{x}_i^T\boldsymbol{\beta}}. During gradient computation, they need ∂μi/∂β=exiTβ⋅xi=μixi\partial \mu_i / \partial \boldsymbol{\beta} = e^{\mathbf{x}_i^T\boldsymbol{\beta}} \cdot \mathbf{x}_i = \mu_i \mathbf{x}_i. The cancellation eln⁡(μi)=μie^{\ln(\mu_i)} = \mu_i is used to substitute μi\mu_i back in, simplifying the Newton-Raphson update without needing to expand the exponential explicitly.

The formula, piece by piece

Breaking the notation:

  • ee: Euler's number, ≈2.71828\approx 2.71828. The base of the natural logarithm and the exponential function.
  • ln⁡x\ln x: natural logarithm of xx; the exponent to which ee must be raised to get xx. Requires x>0x > 0.
  • eln⁡xe^{\ln x}: "raise ee to the power ln⁡x\ln x." Since ln⁡x\ln x is the exponent of ee that gives xx, raising ee to that exponent gives back xx exactly.
  • =x= x: the result. The composed operation is the identity function. Two directions:
  • eln⁡x=xe^{\ln x} = x for x>0x > 0: exponentiating a natural log recovers the argument.
  • ln⁡(ex)=x\ln(e^x) = x for all real xx: taking the natural log of exe^x recovers the exponent. Asymmetry in domain:
  • Direction 1 requires x>0x > 0 (can't take ln⁡\ln of non-positive numbers).
  • Direction 2 has no restriction on xx (since ex>0e^x > 0 for all real xx, ln⁡(ex)\ln(e^x) is always defined). TRAP: base must be ee: elog⁡2x≠xe^{\log_2 x} \ne x.

Since log⁡2x=ln⁡x/ln⁡2\log_2 x = \ln x / \ln 2, we get elog⁡2x=eln⁡x/ln⁡2=x1/ln⁡2≈x1.4427≠xe^{\log_2 x} = e^{\ln x / \ln 2} = x^{1/\ln 2} \approx x^{1.4427} \ne x. The cancellation only works when the exponential base and the logarithm base are the same.

The formula in words

"eln⁡x=xe^{\ln x} = x: raising ee to the natural log of xx gives back xx. The natural log and the exponential with base ee are exact inverses. ln⁡(ex)=x\ln(e^x) = x: the natural log of ee to the xx gives back xx. Use these to: strip ln⁡\ln from an expression by exponentiating both sides; strip e(⋅)e^{(\cdot)} by taking ln⁡\ln of both sides; simplify ln⁡(ef(x))=f(x)\ln(e^{f(x)}) = f(x) directly; re-parameterize positive quantities. TRAP: mismatched bases break the identity."

Critical Concepts

  1. Mutual inverse functions: f(x)=exf(x) = e^x and g(x)=ln⁡xg(x) = \ln x satisfy f(g(x))=xf(g(x)) = x and g(f(x))=xg(f(x)) = x. Their graphs are mirror images across y=xy = x. This is the deepest geometric fact about logarithms and exponentials.
  2. Asymmetric domains: eln⁡x=xe^{\ln x} = x needs x>0x > 0; ln⁡(ex)=x\ln(e^x) = x works for all real xx. In ML, parameters that must be positive (variance, scale, rate) are often re-parameterized as e(⋅)e^{(\cdot)} and then recovered via this identity.
  3. Log-likelihood simplification: exponential family distributions have likelihood functions of the form eT(x)η−A(η)e^{T(x)\eta - A(\eta)}. Taking ln⁡\ln uses ln⁡(ef)=f\ln(e^{f}) = f directly, converting the likelihood to a linear function of the natural parameter η\eta.
  4. Numerically stable softmax: computing ezi/∑jezje^{z_i}/\sum_j e^{z_j} directly overflows for large zz. The stable form subtracts c=max⁡(z)c = \max(z): ezi−c/∑jezj−ce^{z_i - c} / \sum_j e^{z_j - c}, valid because ezi−c=ezi/ece^{z_i - c} = e^{z_i}/e^c and the ece^c cancels. The identity eln⁡(⋅)=(⋅)e^{\ln(\cdot)} = (\cdot) underpins the equivalence.
  5. TRAP: ln⁡(ex)=x\ln(e^x) = x does not mean ln⁡\ln and e(⋅)e^{(\cdot)} commute with all operations: ln⁡(ex+ey)≠x+y\ln(e^x + e^y) \ne x + y.

The cancellation only applies when e(⋅)e^{(\cdot)} is the entire argument to ln⁡\ln, or ln⁡(⋅)\ln(\cdot) is the entire exponent.

Step-by-step calculation (tiny example)

Task: simplify ln⁡(λe−λt)\ln(\lambda e^{-\lambda t}) for the exponential distribution likelihood.

Step 1: Expand using the product rule for logs ln⁡(λe−λt)=ln⁡(λ)+ln⁡(e−λt)\ln(\lambda e^{-\lambda t}) = \ln(\lambda) + \ln(e^{-\lambda t}).

Step 2: Apply ln⁡(ex)=x\ln(e^x) = x to the second term ln⁡(e−λt)=−λt\ln(e^{-\lambda t}) = -\lambda t.

Step 3: Final result ln⁡(λe−λt)=ln⁡λ−λt\ln(\lambda e^{-\lambda t}) = \ln \lambda - \lambda t.

Step 4: Verify at λ=2\lambda = 2, t=0.5t = 0.5 Direct: ln⁡(2⋅e−1)=ln⁡(2/e)=ln⁡2−1≈0.6931−1=−0.3069\ln(2 \cdot e^{-1}) = \ln(2/e) = \ln 2 - 1 \approx 0.6931 - 1 = -0.3069. Formula: ln⁡2−2(0.5)=0.6931−1=−0.3069\ln 2 - 2(0.5) = 0.6931 - 1 = -0.3069.

Step 5: Reverse — reconstruct from log space If ln⁡(μ)=1.5\ln(\mu) = 1.5, then μ=e1.5≈4.4817\mu = e^{1.5} \approx 4.4817. Verify: ln⁡(4.4817)≈1.5\ln(4.4817) \approx 1.5.

Code examples

Beginner example (Python)

python
# Natural log cancellation: e^(ln x) = x and ln(e^x) = x
import math
import numpy as np

# Direction 1: e^(ln x) = x (requires x > 0)
print("Direction 1: e^(ln x) = x")
test_vals = [0.1, 1.0, math.e, 5.0, 100.0, 1e-4]
print(f"{'x':>10} {'ln(x)':>10} {'e^(ln x)':>12} {'matches x':>10}")
for x in test_vals:
    ln_x = math.log(x)
    recovered = math.exp(ln_x)
    print(f"{x:>10.6f} {ln_x:>10.6f} {recovered:>12.6f} {str(abs(recovered - x) < 1e-9):>10}")

# Direction 2: ln(e^x) = x (all real x)
print("\nDirection 2: ln(e^x) = x")
exponents = [-5.0, -1.0, 0.0, 0.5, 1.0, 3.0, 10.0]
print(f"{'x':>8} {'e^x':>14} {'ln(e^x)':>10} {'matches x':>10}")
for x in exponents:
    exp_x = math.exp(x)
    recovered = math.log(exp_x)
    print(f"{x:>8.2f} {exp_x:>14.6f} {recovered:>10.6f} {str(abs(recovered - x) < 1e-9):>10}")

# Exponential distribution log-likelihood simplification
# f(t; lambda) = lambda * e^(-lambda*t)
# ln f = ln(lambda) + ln(e^(-lambda*t)) = ln(lambda) - lambda*t
print("\nExponential distribution: ln(lambda * e^(-lambda*t))")
lam = 2.0
for t in [0.1, 0.5, 1.0, 2.0]:
    direct = math.log(lam * math.exp(-lam * t))
    formula = math.log(lam) - lam * t  # using ln(e^x) = x
    print(f" t={t:.1f}: direct={direct:.6f} formula={formula:.6f} match={abs(direct - formula) < 1e-10}")

# TRAP: mismatched base
print("\nTRAP: e^(log2 x) ≠ x (mismatched base)")
for x in [2.0, 4.0, 8.0]:
    log2_x = math.log2(x)
    e_pow_log2 = math.exp(log2_x)  # e^(log2 x) ≠ x
    print(f" x={x:.0f}: log2(x)={log2_x:.4f} e^(log2 x)={e_pow_log2:.4f} equals x: {abs(e_pow_log2 - x) < 1e-9}")

Beginner example (R)

r
# Natural log cancellation in R: e^(ln x) = x and ln(e^x) = x # Direction 1
cat("Direction 1: exp(log(x)) = x\n")
test_vals <- c(0.1, 1, exp(1), 5, 100)
for (x in test_vals) { recovered <- exp(log(x))
  cat(sprintf(" x=%-10.4f ln(x)=%-10.6f exp(ln x)=%-10.6f match=%s\n", x, log(x), recovered, abs(recovered - x) < 1e-9))
}  # Direction 2
cat("\nDirection 2: log(exp(x)) = x\n")
exponents <- c(-5, -1, 0, 0.5, 1, 3, 10)
for (x in exponents) { recovered <- log(exp(x))
  cat(sprintf(" x=%-6.2f exp(x)=%-14.6f log(exp(x))=%-10.6f match=%s\n", x, exp(x), recovered, abs(recovered - x) < 1e-9))
}  # Exponential distribution log-likelihood
lam <- 2.0
cat("\nExponential log-likelihood: ln(lambda) - lambda*t\n")
for (t in c(0.1, 0.5, 1.0, 2.0)) { direct <- log(lam * exp(-lam * t))
  formula <- log(lam) - lam * t
  cat(sprintf(" t=%.1f: direct=%.6f formula=%.6f match=%s\n", t, direct, formula, abs(direct - formula) < 1e-10))
}

Professional example (Python)

python
import numpy as np
import pandas as pd

# Scenario: unconstrained optimization of a positive parameter
# using the reparameterization sigma = exp(alpha)
# This is the core trick behind log-normal MLE and GLM scale estimation
np.random.seed(42)
N_OBS = 300
TRUE_MU = 3.5
TRUE_SIGMA = 1.2

# Generate log-normal data
raw_data = np.random.lognormal(mean=TRUE_MU, sigma=TRUE_SIGMA, size=N_OBS)


def normal_log_likelihood(data: np.ndarray, mu: float, log_sigma: float) -> float:
    """Log-likelihood of a normal distribution using the reparameterization sigma = exp(log_sigma).

    Applies e^(ln sigma) = sigma to work in unconstrained log_sigma space,
    avoiding the sigma > 0 constraint during optimization.

    Args:
        data: Array of observations (log-transformed raw data).
        mu: Mean parameter (unconstrained).
        log_sigma: Log of standard deviation (unconstrained; sigma = exp(log_sigma)).

    Returns:
        Log-likelihood value.
    """
    sigma = np.exp(log_sigma)  # e^(ln sigma) = sigma — cancellation identity
    n = len(data)
    return float(
        -n * log_sigma  # -n * ln(sigma) = ln(sigma^{-n})
        - n / 2 * np.log(2 * np.pi)
        - 0.5 * np.sum((data - mu) ** 2) / sigma**2
    )


# Evaluate on a grid to find MLE
log_data = np.log(raw_data)  # ln(x) = y such that e^y = x
mu_grid = np.linspace(3.0, 4.0, 50)
log_sig_grid = np.linspace(0.0, 1.0, 50)
best_ll, best_mu, best_log_sigma = -np.inf, 0.0, 0.0
for mu_val in mu_grid:
    for ls_val in log_sig_grid:
        ll = normal_log_likelihood(log_data, mu_val, ls_val)
        if ll > best_ll:
            best_ll, best_mu, best_log_sigma = ll, mu_val, ls_val

best_sigma = np.exp(best_log_sigma)  # recover sigma from log_sigma using e^(ln x) = x

# Report
summary = pd.DataFrame({
    "parameter": ["mu", "sigma", "log_sigma"],
    "true_value": [TRUE_MU, TRUE_SIGMA, np.log(TRUE_SIGMA)],
    "mle_estimate": [best_mu, best_sigma, best_log_sigma],
    "sample_est": [log_data.mean(), log_data.std(), np.log(log_data.std())],
})
print("Log-normal MLE with reparameterization: sigma = exp(log_sigma)")
print("Cancellation identity: exp(ln(sigma)) = sigma used at recovery step")
print("=" * 66)
print(summary.to_string(index=False))
print(f"\nBest grid log-likelihood: {best_ll:.4f}")
print(f"Recovered sigma = exp({best_log_sigma:.4f}) = {best_sigma:.4f} " f"(true: {TRUE_SIGMA:.4f})")

Professional example (R)

r
# Log-normal MLE: sigma = exp(log_sigma), exp(ln(sigma)) = sigma
set.seed(42)
TRUE_SIGMA <- 1.5
x <- exp(rnorm(200, 0, TRUE_SIGMA))
log_sigma_grid <- seq(0.1, 2, by = 0.05)
ll <- sapply(log_sigma_grid, function(ls) {
  sigma <- exp(ls)
  -sum(log(dlnorm(x, 0, sigma)))
})
best_idx <- which.max(ll)
best_log_sigma <- log_sigma_grid[best_idx]
best_sigma <- exp(best_log_sigma)
cat(sprintf("Recovered sigma = exp(%.4f) = %.4f (true: %.4f)\n", best_log_sigma, best_sigma, TRUE_SIGMA))

Source: MFB p. 143

#algebra#exponentials-and-logarithms#definition-and-properties

Keyboard shortcuts

Single keys, ignored while typing in a field or with Cmd, Ctrl or Alt held.

0
Home
1 2 3 4
Work, Writing, Tools, About
j / k
Next / previous section on this page
n / p
Next / previous project or essay
u
Up one level
l
Deutsch
t
Light or dark theme
?
This list
Esc
Close