JuliaMath / SpecialFunctions.jl

Special mathematical functions in Julia
https://specialfunctions.juliamath.org/stable/
Other
358 stars 100 forks source link

`NaN` in `digamma` caused by `_cotpi` #480

Open Youjack opened 1 week ago

Youjack commented 1 week ago

The definition of _digamma(z::ComplexOrReal{Float64}) contains the formula https://github.com/JuliaMath/SpecialFunctions.jl/blob/cf35c580aebd3a698f1d3550e2b60ffbd73bdc0c/src/gamma.jl#L29 in which _cotpi is defined as https://github.com/JuliaMath/SpecialFunctions.jl/blob/cf35c580aebd3a698f1d3550e2b60ffbd73bdc0c/src/gamma.jl#L63 For large complex arguments, _cotpi produces NaN since cospi and sinpi produce Inf. For example,

julia> cospi(500 * exp(im * 3pi/4))
Inf - Inf*im

julia> sinpi(500 * exp(im * 3pi/4))
Inf + Inf*im

julia> cospi(500 * exp(im * 3pi/4)) / sinpi(500 * exp(im * 3pi/4))
NaN + NaN*im

Nevertheless, the ordinary cot gives the correct answer

julia> cot(pi * 500 * exp(im * 3pi/4))
0.0 - 1.0im

A way to avoid NaN is to define cotpi as in mpmath https://github.com/mpmath/mpmath/blob/b600dbcabf4b7406a61e82b9e607f754a9f12ff9/mpmath/libfp.py#L153-L161

stevengj commented 1 week ago

Wouldn't it be better to fix tanpi in base?

Youjack commented 5 days ago

I have added a comment under a tanpi issue in the Julia repo.