Skip to content

Improve accuracy of logexpm1, logcosh, log1pmx and logmxp1 - #136

Merged
devmotion merged 5 commits into
masterfrom
dmw/accuracy-log1pmx-logexpm1-logcosh
Nov 10, 2026
Merged

devmotion merged 5 commits into
masterfrom
dmw/accuracy-log1pmx-logexpm1-logcosh

Conversation

@devmotion

@devmotion devmotion commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Fixes #46, fixes #135.

Changes

  • logexpm1 (and invsoftplus, logitexp, logit1mexp)
    • Thresholds are now derived from the precision by reusing the positive thresholds of log1pexp (_log1pexp_thresholds is split into _log1pexp_thresholds_negative and _log1pexp_thresholds_positive). log(expm1(x)) = x - e⁻ˣ - e⁻²ˣ/2 - … has the same truncation errors as the x + e⁻ˣ branch of log1pexp, so the same cutoffs apply. This replaces the Float64-tuned 18.0/33.3 cutoffs.
    • A BigFloat method mirrors _log1pexp(::BigFloat).
    • Also fixes a Float16 bug: expm1 overflowed for x ≳ 11.09 and returned Inf.
  • logcosh
    • Generic types use log1p(2 sinh(x/2)^2) for |x| < 2. This is cancellation-free at any precision. For |x| ≥ 2 the large-|x| formula loses less than one bit.
    • Float16 keeps its native polynomial kernel. Only the large-|x| branch, which cancels in Float16, is widened to Float32.
  • log1pmx / logmxp1
    • Float16 is computed via Float32.
    • Generic types (e.g. BigFloat) use the atanh series log1p(x) - x = -r x + 2 r t ∑ tᵏ/(2k+3) with r = x/(x+2) and t = r². The series is used for |r| < 1/2, i.e. −2/3 < x < 2; outside, the naive formula loses at most ~2 bits. Inside, cancellation between the two terms amplifies the relative error by at most ~1.11. Summation stops as soon as the sum no longer changes, with an upper bound of cld(precision(x), 2) iterations (t < 1/4).
  • Following the log1pexp pattern, all four functions dispatch on float(x), so Int inputs now use the specialised Float64 implementations.

Accuracy (max ulp error)

before after
log1pmx(::Float16), exhaustive 127 0.5
logmxp1(::Float16), exhaustive 63 0.5
logcosh(::Float16), exhaustive 3.2 1.4
logexpm1(::Float16), x ≥ 11.09 Inf exact
BigFloat (256/512 bits), all 22 functions of #135 on its full grid up to 77 digits lost ≤ 1.03 eps × max(1, cond)

Float32 was already fine (#46). An exhaustive check over all Float32 inputs, using the Float64 implementation as reference, gives max errors of 2.05 ulp (log1pmx on [0, 10)), 2.19 ulp (logmxp1 on [1e-10, 10)), and 2.56 ulp (logcosh on [0, 3)). These exhaustive Float32 checks are not part of the test suite.

ForwardDiff

  • logexpm1, log1pmx, logmxp1 (and the wrappers that call logexpm1): ForwardDiff overloads these through DiffRules. The primal value goes through the fixed Float64/BigFloat paths, and the derivative comes from the DiffRules formula, so these benefit without any Dual-specific change.
  • logcosh has no DiffRule, so Duals use the generic path. On master they always took the cancelling large-|x| formula, because Dual isa Float64 is false.
    • At x = 1e-8, the value had 122% relative error and the derivative a relative error of 6e-9.
    • Both are now within ~1 eps.
    • A DiffRule for logcosh (and logabssinh/logabstanh) in DiffRules.jl is left for a follow-up.

Performance

map! over 10k random inputs for Float32/Float64 is unchanged within noise, and logexpm1(::Float32) is about 15% faster. For BigFloat with 1 ≤ |x| < 2, generic logcosh is 31–38% faster than the large-|x| formula (fewer MPFR temporaries); for Dual{Float64} it is ~3 ns slower on that interval.

Tests

  • Exhaustive Float16 accuracy tests.
  • Dense Float32/Float64 ranges.
  • A BigFloat accuracy testset with all 22 exported single-argument functions of Precision loss for BigFloat in logexpm1, logcosh and log1pmx #135 on the issue's full grid, plus points around the thresholds and branch boundaries, at 256 and 512 bits:
    • As in the issue, the tolerance is 4 eps scaled by the condition number |x f'(x)/f(x)| (via ForwardDiff on the reference), so points near roots such as logitexp(-log(2)) only test the algorithmic error. Exact zeros must be returned exactly.
    • The naive references of logabstanh and cexpexp round to zero at |x| = 1e5 even at high precision (the issue's script silently skipped these points), so they are replaced by cancellation-free references.
    • Against master's implementation this testset fails for exactly the six functions flagged in Precision loss for BigFloat in logexpm1, logcosh and log1pmx #135 (logexpm1, invsoftplus, logitexp, logit1mexp, log1pmx, logcosh) and passes for the other 16.
  • @inferred return-type checks.

Notes

  • The generic log1pmx now requires precision(x) and comparisons. Non-AbstractFloat Reals without them (e.g. symbolic types) previously went through log1p(x) - x. AD types are unaffected since DiffRules/ChainRules intercept log1pmx.

Not addressed

logexpm1 near its root x = log(2) is still inaccurate in ulp terms: about 600–900 ulp for Float32/Float64. A possible fix is log1p(2 expm1(x - log(2))) with a split constant for log(2); that is left for a follow-up PR.

🤖 Generated with Claude Code

- logexpm1: derive thresholds from the precision via `_log1pexp_thresholds`
  instead of hard-coded Float64 cutoffs (fixes up to 61 lost digits for
  BigFloat and overflow of `expm1` for Float16 inputs ≳ 11.09).
- logcosh: use `log1p(2 sinh(x/2)^2)` for small |x| for generic types
  (BigFloat lost all digits for tiny x); widen the large-|x| branch to
  Float32 for Float16 (3.2 -> 1.4 ulp).
- log1pmx/logmxp1: compute Float16 via Float32 (127/63 -> 0.5 ulp); use a
  cancellation-free atanh series for generic types such as BigFloat.
- Integer inputs now dispatch to the specialised Float64 implementations.

Fixes #46, fixes #135.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@tpapp tpapp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM, minor requests for clarification. Rerunning CI would also show if the pipeline failure in julia-min was a glitch (I think yes)

Comment thread src/basicfuns.jl Outdated
# log1p(x) - x = 2 atanh(r) - x = -r x + 2 r t ∑_{k ≥ 0} t^k / (2k + 3),
# where both terms have the same sign, so there is no cancellation.
function _log1pmx(x::Real)
if !(-0.425 < x < 0.4) # same range as for Float32/Float64

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why special case this?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Outside the window the atanh series converges slowly: with r = x/(x+2) and t = r², t → 1 as x → −1 or x → ∞. There the naive log1p(x) - x loses at most about 2 bits to cancellation. The old bounds (−0.425, 0.4) came from the Float32/Float64 method, where they suit the fixed-degree polynomial in _log1pmx_ker: it needs a small interval to reach Float64 accuracy with 9 coefficients. The generic path now uses |r| < 1/2, i.e. −2/3 < x < 2, and the code comment explains this. Tests cover points just inside and outside both boundaries, for BigFloat and for Float64 via invoke.

Comment thread src/basicfuns.jl Outdated
# For x > 0, log(expm1(x)) = x + log1p(-exp(-x)) = x - exp(-x) - exp(-2x)/2 - ...
# The truncation errors match those of `x + exp(-x)` in `_log1pexp`, so the same thresholds apply.
function _logexpm1(x::Real)
_, _, x3, x4 = _log1pexp_thresholds(x)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Given that this is the only place we use those thresholds, would it make sense to just drop x1 and x2? Incidentally, also document _log1pexp_thresholds

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

log1pexp still needs x1 and x2, so I split the function into _log1pexp_thresholds_negative (x1, x2) and _log1pexp_thresholds_positive (x3, x4). logexpm1 is only defined for x ≥ 0 and computes only the positive ones. log1pexp computes them only once x ≥ x2. Both are documented. Float16, Float32 and Float64 still use hard-coded values, and a test checks them against the generic formula.

Comment thread src/basicfuns.jl Outdated
# the upper bound only guards against types with non-IEEE semantics of `+`/`==`.
s = inv(oftype(t, 3))
tk = one(t)
for k in 1:precision(x)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

so maybe guard with

Suggested change
for k in 1:precision(x)
for k in 1:ceiling(Int,precision(x)/3.7)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Done, adapted to the new window: since t < 1/4, after N terms the rest of the sum is at most 4⁻ᴺ/(2N+5) relative to the sum, so the loop now runs at most cld(precision(x), 2) times. It still stops early once adding a term no longer changes the sum; in practice that happens 2–4 iterations before the limit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Int(cld(precision(x), 3.7))?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No, that was a bit too optimistic. It's cld(precision(x), 2) in the PR by now.

@devmotion

Copy link
Copy Markdown
Member Author

Rerunning CI would also show if the pipeline failure in julia-min was a glitch (I think yes)

No, unfortunately it's not. It's a fundamental incompatibility of the glibc in the updated GH runner images and Julia < 1.10.9, see eg JuliaStats/Distributions.jl#2110 (comment). As in Distributions, likely the easiest fix would be to change our tests from min-patch (1.10.0) to min (currently 1.10.9).

- Split `_log1pexp_thresholds` into `_log1pexp_thresholds_negative` (x1, x2)
  and `_log1pexp_thresholds_positive` (x3, x4); `logexpm1` only computes the
  positive ones, and `log1pexp` only computes them if x >= x2.
- Generic `log1pmx`: use the series for |r| < 1/2, i.e. -2/3 < x < 2, and
  bound the number of terms by cld(precision(x), 2).
- Fix comment about cancellation in the series and document the bounds.
- Test the generic `log1pmx` (via `invoke` on Float64) and BigFloat values
  around the window boundaries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
devmotion and others added 3 commits November 9, 2026 15:53
- BigFloat accuracy testset now covers all 22 exported single-argument
  functions on the grids from #135 (plus threshold points), at 256 and 512
  bits, with tolerances scaled by the condition number as in the issue.
  References for logabstanh and cexpexp avoid rounding to zero at |x| = 1e5.
- Generic logcosh uses log1p(2 sinh(x/2)^2) for |x| < 2 instead of |x| < 1:
  more accurate (1.37 -> 1.03 eps at 512 bits) and faster for BigFloat.
- Fix logcosh_ker and log1pmx docstrings, drop stale Julia 1.0/1.6 comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@devmotion
devmotion marked this pull request as ready for review November 9, 2026 18:05
@devmotion
devmotion requested a review from tpapp November 9, 2026 18:05

@tpapp tpapp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Great work, thanks!

@devmotion
devmotion merged commit 7313fda into master Nov 10, 2026
6 checks passed
@tpapp
tpapp deleted the dmw/accuracy-log1pmx-logexpm1-logcosh branch November 12, 2026 09:21
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.

Precision loss for BigFloat in logexpm1, logcosh and log1pmx log1pmxand logmxp1 are probably not optimized for Float32 and Float16

3 participants