From 65025e913246597a385252172275420e7f89be3f Mon Sep 17 00:00:00 2001 From: Alex Arslan Date: Thu, 11 May 2023 16:20:09 -0700 Subject: [PATCH 1/2] Fix `rand` for truncated normal with 0 variance Fixes issues 1712 and 1867. --- src/truncated/normal.jl | 18 +++++++++++++----- test/truncated/normal.jl | 14 +++++++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/truncated/normal.jl b/src/truncated/normal.jl index 6fb334273..904195971 100644 --- a/src/truncated/normal.jl +++ b/src/truncated/normal.jl @@ -128,14 +128,22 @@ function rand(rng::AbstractRNG, d::Truncated{<:Normal{<:Real},Continuous}) d0 = d.untruncated μ = mean(d0) σ = std(d0) + a, b = extrema(d) if isfinite(μ) - lower, upper = extrema(d) - a = (lower - μ) / σ - b = (upper - μ) / σ - z = randnt(rng, a, b, d.tp) + if iszero(σ) + if a <= μ <= b + z = 0.0 + else + throw(ArgumentError("cannot sample from distribution with 0 mass")) + end + else + a′ = (a - μ) / σ + b′ = (b - μ) / σ + z = randnt(rng, a′, b′, d.tp) + end return μ + σ * z else - return clamp(μ, extrema(d)...) + return clamp(μ, a, b) end end diff --git a/test/truncated/normal.jl b/test/truncated/normal.jl index 9d287c026..5850c5912 100644 --- a/test/truncated/normal.jl +++ b/test/truncated/normal.jl @@ -47,7 +47,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 @@ -69,3 +69,15 @@ 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_throws ArgumentError rand(truncated(d, 6, 9)) # μ ∉ [a, b] + # https://github.com/JuliaStats/Distributions.jl/issues/1867 + d = Normal(1, 0) + @test rand(truncated(Normal(1, 0), 0, 1)) == 1 + @test rand(truncated(Normal(0, 0), 0, 1)) == 0 +end From 5c79db14e9de4da60e85f28aec2987bb2ca9489d Mon Sep 17 00:00:00 2001 From: Alex Arslan Date: Thu, 15 Aug 2024 10:06:38 -0700 Subject: [PATCH 2/2] Bump patch version --- Project.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index c05283276..af12e4b7a 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "Distributions" uuid = "31c24e10-a181-5473-b8eb-7969acd0382f" authors = ["JuliaStats"] -version = "0.25.110" +version = "0.25.111" [deps] AliasTables = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"