Skip to content

Commit 73f64dd

Browse files
simsuracedevmotion
andauthored
Allow sampling NegativeBinomial for p==1 (#1575)
* Allow sampling `NegativeBinomial` for `p==1` * Draw multiple samples Co-authored-by: David Widmann <devmotion@users.noreply.github.com> Co-authored-by: David Widmann <devmotion@users.noreply.github.com>
1 parent 7831193 commit 73f64dd

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

src/univariate/discrete/negativebinomial.jl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,13 @@ invlogcdf(d::NegativeBinomial, lq::Real) = convert(Int, nbinominvlogcdf(d.r, d.p
118118
invlogccdf(d::NegativeBinomial, lq::Real) = convert(Int, nbinominvlogccdf(d.r, d.p, lq))
119119

120120
## sampling
121-
rand(rng::AbstractRNG, d::NegativeBinomial) = rand(rng, Poisson(rand(rng, Gamma(d.r, (1 - d.p)/d.p))))
121+
function rand(rng::AbstractRNG, d::NegativeBinomial)
122+
if isone(d.p)
123+
return 0
124+
else
125+
return rand(rng, Poisson(rand(rng, Gamma(d.r, (1 - d.p)/d.p))))
126+
end
127+
end
122128

123129
function mgf(d::NegativeBinomial, t::Real)
124130
r, p = params(d)

test/negativebinomial.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ end
1717
@testset "Check the corner case p==1" begin
1818
@test logpdf(NegativeBinomial(0.5, 1.0), 0) === 0.0
1919
@test logpdf(NegativeBinomial(0.5, 1.0), 1) === -Inf
20+
@test all(iszero, rand(NegativeBinomial(rand(), 1.0), 10))
2021
end

0 commit comments

Comments
 (0)