Skip to content

Commit

Permalink
Fix Wrong quantiles calculated for some Truncated #1726 (#1727)
Browse files Browse the repository at this point in the history
* Fix Wrong quantiles calculated for some Truncated #1726

As described in
[#1726](#1726), there occur small numbers-big number problems while evaluating quantiles on `Truncated`.

This Fix uses the knowledge on the upper bound of `Truncated` to properly limit the output.

* Update src/truncate.jl

* Update unittest

---------

Co-authored-by: David Widmann <devmotion@users.noreply.github.com>
  • Loading branch information
waldie11 and devmotion authored Jun 19, 2023
1 parent 6251044 commit c480dc0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/truncate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,11 @@ end

### evaluation

quantile(d::Truncated, p::Real) = quantile(d.untruncated, d.lcdf + p * d.tp)
function quantile(d::Truncated, p::Real)
x = quantile(d.untruncated, d.lcdf + p * d.tp)
min_x, max_x = extrema(d)
return clamp(x, oftype(x, min_x), oftype(x, max_x))
end

function pdf(d::Truncated, x::Real)
result = pdf(d.untruncated, x) / d.tp
Expand Down
17 changes: 17 additions & 0 deletions test/truncate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,20 @@ end
x = rand(d, 10_000)
@test mean(x) 0.5 atol=0.05
end

@testset "quantile examples (#1726)" begin
d_narrow = truncated(Normal(0, 0.01), -1, 1.2)

# prior to patch #1727 this was offering either ±Inf
@test quantile(d_narrow, 1) d_narrow.upper && quantile(d_narrow, 1) d_narrow.upper
@test quantile(d_narrow, 0) d_narrow.lower && quantile(d_narrow, 0) d_narrow.lower

@test isa(quantile(d_narrow, ForwardDiff.Dual(0., 0.)), ForwardDiff.Dual)

d = truncated(Normal(0, 2), 0, 1)

# prior to patch #1727 this was offering 1.0000000000000002 > 1.
@test quantile(d, 1) d.upper && quantile(d, 1) d.upper

@test isa(quantile(d, ForwardDiff.Dual(1.,0.)), ForwardDiff.Dual)
end

0 comments on commit c480dc0

Please sign in to comment.