Skip to content

Commit

Permalink
Fix rand for truncated normal with 0 variance
Browse files Browse the repository at this point in the history
Fixes issue 1712.
  • Loading branch information
ararslan committed May 11, 2023
1 parent fa8c30d commit b488b3c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/truncated/normal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,18 @@ function rand(rng::AbstractRNG, d::Truncated{Normal{T},Continuous}) where T <: R
μ = mean(d0)
σ = std(d0)
if isfinite(μ)
a = (d.lower - μ) / σ
b = (d.upper - μ) / σ
z = randnt(rng, a, b, d.tp)
a, b = extrema(d)
if iszero(σ)
if a <= μ <= b
z = 0.0
else
return NaN
end
else
a′ = (a - μ) / σ
b′ = (b - μ) / σ
z = randnt(rng, a′, b′, d.tp)
end
return μ + σ * z
else
return clamp(μ, d.lower, d.upper)
Expand Down
10 changes: 9 additions & 1 deletion test/truncated/normal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ end
[(r = rand, r! = rand!),
(r = ((d, n) -> rand(rng, d, n)), r! = ((d, X) -> rand!(rng, d, X)))]
repeats = 1000000

@test abs(mean(func.r(trunc, repeats))) < 0.01
@test abs(median(func.r(trunc, repeats))) < 0.01
@test abs(var(func.r(trunc, repeats)) - var(trunc)) < 0.01
Expand All @@ -67,3 +67,11 @@ end
@test isfinite(pdf(trunc, x))
end
end

@testset "Degenerate truncated normal" begin
# https://github.com/JuliaStats/Distributions.jl/issues/1712
d = Normal(2, 0)
@test rand(truncated(d, 2, 2)) == 2 # a == μ == b
@test rand(truncated(d, 1, 3)) == 2 # a <= μ <= b
@test isnan(rand(truncated(d, 6, 9))) # μ ∉ [a, b]
end

0 comments on commit b488b3c

Please sign in to comment.