Skip to content

Add log1pdiv and expm1div. - #143

Open
tpapp wants to merge 4 commits into
masterfrom
tp/log1pdiv_expm1div
Open

tpapp wants to merge 4 commits into
masterfrom
tp/log1pdiv_expm1div

Conversation

@tpapp

@tpapp tpapp commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Fixes #142.

Coded with deepseek-v4.1-flash.

@tpapp
tpapp requested a review from devmotion November 27, 2026 13:09

@devmotion devmotion left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked numerical accuracy against BigFloat references (Float64/Float32, nested ForwardDiff 1.5.0, Julia 1.13).

Max error of the primals was 1.24 ulp (log1pdiv) and 1.29 ulp (expm1div) over ±[1e-300, 600], ≤ 2.5 ulp on 705–717 where expm1(x) overflows, and same cost as the naive log1p(x)/x / expm1(x)/x (~5–7 ns).

The functions are problematic for ForwardDiff though. Without a DiffRules entry or an explicit rule, the Dual goes through log1p(x)/x and expm1(x)/x (in ForwardDiff ≥ 1, iszero(Dual(0, 1)) is false, so the iszero branch is not taken):

x ForwardDiff.derivative(log1pdiv, x) ForwardDiff.derivative(expm1div, x)
0.0, -0.0 NaN NaN
1e-300, 1e-20 0.0 0.0
1e-10 off by 7.5e8 ulp off by 3.7e8 ulp
1e-6 off by 8.5e5 ulp off by 2.3e5 ulp
1e-3 off by 3.0e3 ulp off by 286 ulp

The second derivative at 0 is NaN as well. I expect Enzyme and Mooncake to have the same problem near 0, since they also differentiate the primal (not verified).

Maybe we could move _∂_log1pdiv / _∂_expm1div from the extension to src so they're available without ChainRulesCore (maybe make them public and use a more official name?), then DiffRules.jl could add a rule based on them (or Enzyme, ForwardDiff etc. could a direct rule if needed) once this PR is released.

Naming / references. (exp(x) - 1)/x is exprel in SciPy (scipy.special.exprel) and GSL (gsl_sf_exprel), and φ₁ in the exponential-integrator literature (ExponentialUtilities.jl phi, EXPINT; Higham, Functions of Matrices, §10.7.4). I'm fine with expm1div/log1pdiv since they match log1pmx/logmxp1 here, but it would help to mention the aliases in the docstrings. I did not find a standard name for log1p(x)/x.

I think an InverseFunctions definition might not be needed here. Both functions are bijections onto (0, ∞), but the inverses need the Lambert W function (e.g. expm1div⁻¹(y) = -1/y - W(-exp(-1/y)/y) on the non-trivial branch).

In the tests, maybe we could also check log1pdiv(expm1(s)) ≈ 1/expm1div(s) as a cheap cross-check between the two functions?

I was also wondering whether one could exploit that both functions are in families are closed under differentiation: φₖ(x) = ₁F₁(1; k+1; x)/k! with φₖ' = φₖ − k φₖ₊₁ and log1pdiv(x) = ₂F₁(1, 1; 2; -x) with n-th derivative (−1)ⁿ n!/(n+1) ₂F₁(n+1, n+1; n+2; −x). It seems cute but I couldn't immediately see how it would be useful here.

Comment thread src/basicfuns.jl Resolved
# `logmxp1(1 / (1 + x))` (`log(y) - y + 1` at `y = 1 / (1 + x)`), which is accurate; `/ x / x`
# avoids the overflow of `x^2`.
function _∂_log1pdiv(x::Real)
if abs(x) < 0.5

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I first wanted to suggest replacing this loop with a closed form or a fixed-degree polynomial, but measured with nested ForwardDiff (relative error of f⁽ⁿ⁺¹⁾ vs BigFloat), the adaptive series is the AD-safe choice near 0:

x f'' f⁽³⁾ f⁽⁴⁾ f⁽⁵⁾
this loop 1e-5 … ±0.45 ≤ 1e-15 ≤ 1e-15 ≤ 1e-14 ≤ 1.6e-13
4-term Taylor poly 1e-5 4.8e-15 6.7e-10 4.2e-5 1.0 (exactly 0)
log1pmx(-x / (1 + x)) / x / x 1e-3 1.4e-13 1.1e-10 9.6e-8 8.3e-5

A truncated polynomial loses one degree per derivative order. Closed forms divided by x^2 lose about a factor 1/x per order to cancellation.

Two remarks, though:

  1. The loop is AD-safe only because, in ForwardDiff ≥ 1, == on Duals compares the partials too, so s_new == s waits until the derivatives have converged as well. Please document this in a comment and add a nested-ForwardDiff test, so that nobody "optimizes" it into a fixed-degree polynomial later.
  2. It's slow: since the coefficients (k + 1)/(k + 2) have no factorial, the series converges only geometrically. I measured 13/17/24/64 ns at x = 0.05/0.1/0.2/0.49. Optionally the window could shrink to abs(x) < 0.3; beyond that the closed form below has ≤ 1.8e-14 relative error up to f⁽⁵⁾. Note that logmxp1(inv(1 + x)) and log1pmx(-x / (1 + x)) are the same function; they differ only in which quantity is rounded (w = 1/(1 + x) vs u = x/(1 + x)). The former is better for large x, so the PR's choice is right there.

Comment thread ext/LogExpFunctionsChainRulesCoreExt.jl Resolved
Comment on lines +150 to +151
function _∂_expm1div(x::Real)
if abs(x) < 2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The abs(x) < 2 window can shrink to abs(x) < 1, using exact closed forms outside it:

  • x ≥ 1: (Ω (x - 1) + 1) / x with Ω = expm1div(x), i.e., expm1div(x) * (1 - inv(x)) + inv(x). No cancellation, and finite as long as Ω is (up to ~716). In the @scalar_rule you could pass Ω instead of recomputing it.
  • x ≤ -1: (x * exp(x) - expm1(x)) / x / x, which is eˣ φ₂(-x) (φ₁' = φ₁ − φ₂ = eˣ φ₂(−x)).
function _∂_expm1div(x::Real)
    isinf(x) && return x > 0 ? x : zero(x)
    x >= 1 && return expm1div(x) * (1 - inv(x)) + inv(x)
    x <= -1 && return (x * exp(x) - expm1(x)) / x / x
    # adaptive series for `-1 < x < 1`, as before
    ...
end

Measured: same worst case as the PR (4.7 ulp Float64, 3.5 ulp Float32, now attained on the series part near x = -0.45), correct at ±Inf, ~5 ns instead of 13–18 ns for 1 ≤ |x| < 2, and nested ForwardDiff stays accurate (relative error ≤ 4e-15 up to f⁽⁴⁾ at x = ±1).

Optional: the cancellation in the alternating series for x < 0 can be avoided with Kummer's transformation ₁F₁(2; 3; x) = eˣ ₁F₁(1; 3; -x), i.e., φ₁'(x) = exp(x) * ∑ₖ (-x)ᵏ/(k + 2)!, a series with only positive terms (2.15 ulp on [-2, 0] in my test). It must remain adaptive, though, not a fixed-degree polynomial (see my comment on _∂_log1pdiv).

h = exp(x / 2)
return h * ((x - 1) / x) * (h / x) + inv(x)^2
end
return (exp(x) * (x - 1) + one(x)) / x / x

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_∂_expm1div(Inf) and _∂_expm1div(-Inf) return NaN (Inf/Inf in the x > 0 branch, 0 * -Inf here), while expm1div(±Inf) is handled. The limits are Inf and 0; see the snippet above.

Comment thread test/chainrules.jl
f === log1pdiv && !(x > -1) && continue
rT = T(∂ref(x))
(isfinite(rT) && !iszero(rT)) || continue
@test ulp_error(BigFloat(rT), ∂f(x)) < 6

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add:

  • the special values ±Inf (and -1 for log1pdiv);
  • ForwardDiff tests at 0, -0.0 and near 0 (currently NaN/wrong, see the summary), once the DiffRules rules exist;
  • nested-ForwardDiff tests (2nd and 3rd derivatives of the helpers) against BigFloat references, e.g., at 0, 1e-5, ±0.4, ±1.5, so that the AD-safety of the adaptive series is protected;
  • log1pdiv(expm1(s)) ≈ 1/expm1div(s) as a cross-check.

tpapp and others added 2 commits November 29, 2026 08:17
Co-authored-by: David Müller-Widmann <devmotion@users.noreply.github.com>
Co-authored-by: David Müller-Widmann <devmotion@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

log(1+x)/x, (exp(x)-1)/x

2 participants