Skip to content

Commit a57c72e

Browse files
freebosonsimonbyrne
authored andcommitted
add lbinomial (#99)
1 parent c0f1c03 commit a57c72e

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

src/SpecialFunctions.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ else
6868
end
6969

7070
export sinint,
71-
cosint
71+
cosint,
72+
lbinomial
7273

7374
include("bessel.jl")
7475
include("erf.jl")

src/gamma.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,3 +769,25 @@ const lfactorial = lfact
769769
export lfactorial
770770

771771
end # @static if
772+
773+
"""
774+
lbinomial(n, k) = log(abs(binomial(n, k)))
775+
776+
Accurate natural logarithm of the absolute value of the [`binomial`](@ref)
777+
coefficient `binomial(n, k)` for large `n` and `k` near `n/2`.
778+
"""
779+
function lbinomial(n::T, k::T) where {T<:Integer}
780+
S = float(T)
781+
(k < 0) && return typemin(S)
782+
if n < 0
783+
n = -n + k - 1
784+
end
785+
k > n && return typemin(S)
786+
(k == 0 || k == n) && return zero(S)
787+
(k == 1) && return log(abs(n))
788+
if k > (n>>1)
789+
k = n - k
790+
end
791+
-log1p(n) - lbeta(n - k + one(T), k + one(T))
792+
end
793+
lbinomial(n::Integer, k::Integer) = lbinomial(promote(n, k)...)

test/runtests.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,18 @@ end
642642
@test beta(big(1.0),big(1.2)) beta(1.0,1.2) rtol=4*eps()
643643
end
644644

645+
@testset "lbinomial" begin
646+
@test lbinomial(10, -1) == -Inf
647+
@test lbinomial(10, 11) == -Inf
648+
@test lbinomial(10, 0) == 0.0
649+
@test lbinomial(10, 10) == 0.0
650+
651+
@test lbinomial(10, 1) log(10)
652+
@test lbinomial(-6, 10) log(binomial(-6, 10))
653+
@test lbinomial(-6, 11) log(abs(binomial(-6, 11)))
654+
@test lbinomial.(200, 0:200) log.(binomial.(BigInt(200), (0:200)))
655+
end
656+
645657
@static if isdefined(Base, :missing)
646658
@testset "missing data" begin
647659
for f in (digamma, erf, erfc, erfcinv, erfcx, erfi, erfinv, eta, gamma,

0 commit comments

Comments
 (0)