Repository navigation
Improve accuracy of logexpm1, logcosh, log1pmx and logmxp1 - #136
Conversation
- 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
left a comment
There was a problem hiding this comment.
LGTM, minor requests for clarification. Rerunning CI would also show if the pipeline failure in julia-min was a glitch (I think yes)
| # 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 |
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
so maybe guard with
| for k in 1:precision(x) | |
| for k in 1:ceiling(Int,precision(x)/3.7) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Int(cld(precision(x), 3.7))?
There was a problem hiding this comment.
No, that was a bit too optimistic. It's cld(precision(x), 2) in the PR by now.
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 |
- 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]>
- 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]>
Fixes #46, fixes #135.
Changes
logexpm1(andinvsoftplus,logitexp,logit1mexp)log1pexp(_log1pexp_thresholdsis split into_log1pexp_thresholds_negativeand_log1pexp_thresholds_positive).log(expm1(x)) = x - e⁻ˣ - e⁻²ˣ/2 - …has the same truncation errors as thex + e⁻ˣbranch oflog1pexp, so the same cutoffs apply. This replaces the Float64-tuned18.0/33.3cutoffs._log1pexp(::BigFloat).expm1overflowed for x ≳ 11.09 and returnedInf.logcoshlog1p(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.log1pmx/logmxp1log1p(x) - x = -r x + 2 r t ∑ tᵏ/(2k+3)withr = x/(x+2)andt = 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 ofcld(precision(x), 2)iterations (t < 1/4).log1pexppattern, all four functions dispatch onfloat(x), soIntinputs now use the specialised Float64 implementations.Accuracy (max ulp error)
log1pmx(::Float16), exhaustivelogmxp1(::Float16), exhaustivelogcosh(::Float16), exhaustivelogexpm1(::Float16), x ≥ 11.09InfFloat32 was already fine (#46). An exhaustive check over all Float32 inputs, using the Float64 implementation as reference, gives max errors of 2.05 ulp (
log1pmxon [0, 10)), 2.19 ulp (logmxp1on [1e-10, 10)), and 2.56 ulp (logcoshon [0, 3)). These exhaustive Float32 checks are not part of the test suite.ForwardDiff
logexpm1,log1pmx,logmxp1(and the wrappers that calllogexpm1): 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.logcoshhas no DiffRule, soDuals use the generic path. On master they always took the cancelling large-|x| formula, becauseDual isa Float64is false.logcosh(andlogabssinh/logabstanh) in DiffRules.jl is left for a follow-up.Performance
map!over 10k random inputs for Float32/Float64 is unchanged within noise, andlogexpm1(::Float32)is about 15% faster. For BigFloat with 1 ≤ |x| < 2, genericlogcoshis 31–38% faster than the large-|x| formula (fewer MPFR temporaries); forDual{Float64}it is ~3 ns slower on that interval.Tests
|x f'(x)/f(x)|(via ForwardDiff on the reference), so points near roots such aslogitexp(-log(2))only test the algorithmic error. Exact zeros must be returned exactly.logabstanhandcexpexpround 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.logexpm1,invsoftplus,logitexp,logit1mexp,log1pmx,logcosh) and passes for the other 16.@inferredreturn-type checks.Notes
log1pmxnow requiresprecision(x)and comparisons. Non-AbstractFloatReals without them (e.g. symbolic types) previously went throughlog1p(x) - x. AD types are unaffected since DiffRules/ChainRules interceptlog1pmx.Not addressed
logexpm1near its root x = log(2) is still inaccurate in ulp terms: about 600–900 ulp for Float32/Float64. A possible fix islog1p(2 expm1(x - log(2)))with a split constant for log(2); that is left for a follow-up PR.🤖 Generated with Claude Code