Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/LogExpFunctions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import LinearAlgebra

export xlogx, xlogy, xlog1py, xexpx, xexpy, logistic, logit, log1psq, log1pexp, log1mexp, log2mexp, logexpm1,
softplus, invsoftplus, log1pmx, logmxp1, logaddexp, logsubexp, logsumexp, logsumexp!, softmax,
softmax!, logcosh, logabssinh, cloglog, cexpexp,
softmax!, logcosh, logabssinh, logabstanh, cloglog, cexpexp,
loglogistic, logitexp, log1mlogistic, logit1mexp

# expm1(::Float16) is not defined in older Julia versions,
Expand Down
25 changes: 25 additions & 0 deletions src/basicfuns.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,31 @@ end
"""
$(SIGNATURES)

Return `log(abs(tanh(x)))`, carefully evaluated without intermediate calculation of `tanh(x)`.

The implementation ensures `logabstanh(-x) = logabstanh(x)`.
"""
function logabstanh(x::Real)
return log1p(-2/((exp(2abs(x))+1)))
Copy link
Member

Choose a reason for hiding this comment

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

As indicated by the special cases close to 0 for Float32 and Float64, maybe a safer default would be

Suggested change
return log1p(-2/((exp(2abs(x))+1)))
return log(abs(tanh(x)))

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think the version I wrote stays more accurate overall but I'll do a test

Copy link
Member

Choose a reason for hiding this comment

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

I don't think it's possible to do such an analysis? You can't realistically test any subtype of Real.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

for any AbstractFloat log(tanh(x)) will be inaccurate for large x since tanh(x) will be very close to 1.

end
function logabstanh(x::Float32)
abs_x = abs(x)
if abs_x < 0.0625f0
return log(abs_x) - x*x*(1f0/3)
end
return log1p(-2/((exp(2abs_x)+1)))
end
function logabstanh(x::Float64)
abs_x = abs(x)
if abs_x < 0x1p-5
return log(abs_x) + evalpoly(x*x, (0, -1/3, 7/90, -62/2835))
end
return log1p(-2/((exp(2abs_x)+1)))
end

"""
$(SIGNATURES)

Return `log(1+x^2)` evaluated carefully for `abs(x)` very small or very large.
"""
log1psq(x::Real) = log1p(abs2(x))
Expand Down
Loading