Skip to content

Commit

Permalink
Merge pull request #359 from jamesonquinn/BetaDistInfIssue350
Browse files Browse the repository at this point in the history
Avoid Inf from logpdf(::Beta,...) (issue #350)
  • Loading branch information
marcoct authored Feb 15, 2021
2 parents 3a2aedb + dbcb124 commit feaa178
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ authors = ["Marco Cusumano-Towner <[email protected]>"]
version = "0.4.1"

[deps]
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"
Expand Down
10 changes: 9 additions & 1 deletion src/modeling_library/distributions/beta.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@ const beta = Beta()

function logpdf(::Beta, x::Real, alpha::Real, beta::Real)
(x < 0 || x > 1 ? -Inf :
(alpha - 1) * log(x) + (beta - 1) * log1p(-x) - logbeta(alpha, beta) )
((x == 0 && alpha <= 1) ? #Special case to avoid infinite PDF at 0
(alpha - 1) * log(eps(typeof(x))) -
alpha + 1 + #as if we were using x=(eps / e); even smaller than eps
(beta - 1) * log1p(-eps(typeof(x))) - logbeta(alpha, beta) :
((x == 1 && beta <= 1) ? #Special case to avoid infinite PDF at 1
(alpha - 1) * log1p(-eps(typeof(x))) -
beta + 1 + #as if we were using 1-x=(eps / e)
(beta - 1) * log(eps(typeof(x))) - logbeta(alpha, beta) :
(alpha - 1) * log(x) + (beta - 1) * log1p(-x) - logbeta(alpha, beta) )))
end

function logpdf_grad(::Beta, x::Real, alpha::Real, beta::Real)
Expand Down
6 changes: 6 additions & 0 deletions test/modeling_library/distributions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ end
# out of support
@test logpdf(beta, -1, 0.5, 0.5) == -Inf

# avoid infinities, sanely
@test logpdf(beta, eps(typeof(0.)), 0.5, 0.5) < logpdf(beta, 0., 0.5, 0.5) < Inf
@test logpdf(beta, eps(typeof(0.)), 0.5, 1.5) < logpdf(beta, 0., 0.5, 1.5) < Inf
@test logpdf(beta, 1-eps(typeof(0.)), 0.5, 0.5) < logpdf(beta, 1., 0.5, 0.5) < Inf
@test logpdf(beta, 1-eps(typeof(0.)), 1.5, 0.5) < logpdf(beta, 1., 1.5, 0.5) < Inf

# logpdf_grad
f = (x, alpha, beta_param) -> logpdf(beta, x, alpha, beta_param)
args = (0.4, 0.2, 0.3)
Expand Down

0 comments on commit feaa178

Please sign in to comment.