Skip to content

Commit 75436e4

Browse files
oscardssmithgiordano
authored andcommitted
simplify complex atanh and remove singularity perturbation (#55268)
fixes #55266, and use `inv(z)` rather than `1/z` and use `muladd` in a couple places. --------- Co-authored-by: Mosè Giordano <[email protected]> (cherry picked from commit b7aa5e3)
1 parent ecdbb39 commit 75436e4

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

base/complex.jl

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,24 +1028,22 @@ end
10281028
function atanh(z::Complex{T}) where T
10291029
z = float(z)
10301030
Tf = float(T)
1031-
Ω = prevfloat(typemax(Tf))
1032-
θ = sqrt(Ω)/4
1033-
ρ = 1/θ
10341031
x, y = reim(z)
10351032
ax = abs(x)
10361033
ay = abs(y)
1034+
θ = sqrt(floatmax(Tf))/4
10371035
if ax > θ || ay > θ #Prevent overflow
10381036
if isnan(y)
10391037
if isinf(x)
10401038
return Complex(copysign(zero(x),x), y)
10411039
else
1042-
return Complex(real(1/z), y)
1040+
return Complex(real(inv(z)), y)
10431041
end
10441042
end
10451043
if isinf(y)
10461044
return Complex(copysign(zero(x),x), copysign(oftype(y,pi)/2, y))
10471045
end
1048-
return Complex(real(1/z), copysign(oftype(y,pi)/2, y))
1046+
return Complex(real(inv(z)), copysign(oftype(y,pi)/2, y))
10491047
end
10501048
β = copysign(one(Tf), x)
10511049
z *= β
@@ -1055,16 +1053,15 @@ function atanh(z::Complex{T}) where T
10551053
ξ = oftype(x, Inf)
10561054
η = y
10571055
else
1058-
ym = ay+ρ
1059-
ξ = log(sqrt(sqrt(4+y*y))/sqrt(ym))
1060-
η = copysign(oftype(y,pi)/2 + atan(ym/2), y)/2
1056+
ξ = log(sqrt(sqrt(muladd(y, y, 4)))/sqrt(ay))
1057+
η = copysign(oftype(y,pi)/2 + atan(ay/2), y)/2
10611058
end
10621059
else #Normal case
1063-
ysq = (ay+ρ)^2
1060+
ysq = ay^2
10641061
if x == 0
10651062
ξ = x
10661063
else
1067-
ξ = log1p(4x/((1-x)^2 + ysq))/4
1064+
ξ = log1p(4x/(muladd(1-x, 1-x, ysq)))/4
10681065
end
10691066
η = angle(Complex((1-x)*(1+x)-ysq, 2y))/2
10701067
end

test/complex.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1214,3 +1214,9 @@ end
12141214
@test !iseven(7+0im) && isodd(7+0im)
12151215
@test !iseven(6+1im) && !isodd(7+1im)
12161216
end
1217+
1218+
@testset "issue #55266" begin
1219+
for T in (Float16, Float32, Float64)
1220+
@test isapprox(atanh(1+im*floatmin(T)), Complex{T}(atanh(1+im*big(floatmin(T)))))
1221+
end
1222+
end

0 commit comments

Comments
 (0)