Skip to content

Commit 055bbe4

Browse files
committed
fixed type-stability of chorner and polygamma (workaround for JuliaLang#7060)
1 parent 76a7335 commit 055bbe4

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

base/math.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ macro chorner(z, p...)
7070
:(r = x + x),
7171
:(s = x*x + y*y),
7272
as...,
73-
:(Complex($ai * x + $b, $ai * y)))
73+
:($ai * $(esc(z)) + $b))
7474
R = Expr(:macrocall, symbol("@horner"), esc(z), p...)
7575
:(isa($(esc(z)), Real) ? $R : $C)
7676
end

base/special/gamma.jl

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,9 @@ function inv_oftype(x::Complex, y::Real)
224224
end
225225
inv_oftype(x::Real, y::Real) = oftype(x, inv(y))
226226

227+
zeta_returntype{T}(s::Integer, z::T) = T
228+
zeta_returntype(s, z) = Complex128
229+
227230
# Hurwitz zeta function, which is related to polygamma
228231
# (at least for integer m > 0 and real(z) > 0) by:
229232
# polygamma(m, z) = (-1)^(m+1) * gamma(m+1) * zeta(m+1, z).
@@ -237,21 +240,21 @@ inv_oftype(x::Real, y::Real) = oftype(x, inv(y))
237240
# (which Julia already exports).
238241
function zeta(s::Union(Int,Float64,Complex{Float64}),
239242
z::Union(Float64,Complex{Float64}))
240-
ζ = isa(s, Int) ? zero(z) : complex(zero(z))
243+
ζ = zero(zeta_returntype(s, z))
241244
z == 1 && return oftype(ζ, zeta(s))
242245
s == 2 && return oftype(ζ, trigamma(z))
243246

244247
x = real(z)
245248

246249
# annoying s = Inf or NaN cases:
247250
if !isfinite(s)
248-
(isnan(s) || isnan(z)) && return Complex(NaN, NaN)
251+
(isnan(s) || isnan(z)) && return (s*z)^2 # type-stable NaN+Nan*im
249252
if real(s) == Inf
250253
z == 1 && return one(ζ)
251254
if x > 1 || (x >= 0.5 ? abs(z) > 1 : abs(z - round(x)) > 1)
252255
return zero(ζ) # distance to poles is > 1
253256
end
254-
x > 0 && imag(z) == 0 && imag(s) == 0 && return Complex(Inf, 0.0)
257+
x > 0 && imag(z) == 0 && imag(s) == 0 && return oftype(ζ, Inf)
255258
end
256259
throw(DomainError()) # nothing clever to return
257260
end

test/math.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,6 @@ end
274274
@test polygamma(4, -0.0) == Inf == -polygamma(4, +0.0)
275275
@test zeta(4, +0.0) == Inf == zeta(4, -0.0)
276276
@test zeta(5, +0.0) == Inf == -zeta(5, -0.0)
277+
@test isa([digamma(x) for x in [1.0]], Vector{Float64})
278+
@test isa([trigamma(x) for x in [1.0]], Vector{Float64})
279+
@test isa([polygamma(3,x) for x in [1.0]], Vector{Float64})

0 commit comments

Comments
 (0)