Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw an error when truncating outside of support #1723

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/truncate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ function truncated(d::UnivariateDistribution, l::T, u::T) where {T <: Real}
ucdf = exp(logucdf)

# (log)tp = (log) P(l ≤ X ≤ u) where X ∼ d
logtp = logsubexp(loglcdf, logucdf)
logtp = if d isa DiscreteUnivariateDistribution
logaddexp(logdiffcdf(d, u, l), logpdf(d, l))
else
logdiffcdf(d, u, l)
end
tp = exp(logtp)

Truncated(d, promote(l, u, loglcdf, lcdf, ucdf, tp, logtp)...)
Expand All @@ -95,6 +99,9 @@ struct Truncated{D<:UnivariateDistribution, S<:ValueSupport, T<: Real, TL<:Union
logtp::T # log(tp), i.e. log(ucdf - lcdf)

function Truncated(d::UnivariateDistribution, l::TL, u::TU, loglcdf::T, lcdf::T, ucdf::T, tp::T, logtp::T) where {T <: Real, TL <: Union{T,Nothing}, TU <: Union{T,Nothing}}
if logtp == -Inf
throw(ArgumentError("cannot truncate distribution; `$d` has 0 probability in the interval `[$l, $u]`"))
end
new{typeof(d), value_support(typeof(d)), T, TL, TU}(d, l, u, loglcdf, lcdf, ucdf, tp, logtp)
end
end
Expand Down
5 changes: 5 additions & 0 deletions test/truncate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,8 @@ end
x = rand(d, 10_000)
@test mean(x) ≈ 0.5 atol=0.05
end

@testset "truncation outside support (#843)" begin
@test_throws ArgumentError truncated(Exponential(), -3, -1) # truncated region outside support
@test_throws ArgumentError truncated(Normal(2, 0), 0, 1) # point mass outside truncated region
end