Skip to content

Commit feaa178

Browse files
authored
Merge pull request #359 from jamesonquinn/BetaDistInfIssue350
Avoid Inf from logpdf(::Beta,...) (issue #350)
2 parents 3a2aedb + dbcb124 commit feaa178

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Project.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ authors = ["Marco Cusumano-Towner <[email protected]>"]
44
version = "0.4.1"
55

66
[deps]
7+
Compat = "34da2185-b29b-5c13-b0c7-acf172513d20"
78
DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
89
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
910
ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210"

src/modeling_library/distributions/beta.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,15 @@ const beta = Beta()
1212

1313
function logpdf(::Beta, x::Real, alpha::Real, beta::Real)
1414
(x < 0 || x > 1 ? -Inf :
15-
(alpha - 1) * log(x) + (beta - 1) * log1p(-x) - logbeta(alpha, beta) )
15+
((x == 0 && alpha <= 1) ? #Special case to avoid infinite PDF at 0
16+
(alpha - 1) * log(eps(typeof(x))) -
17+
alpha + 1 + #as if we were using x=(eps / e); even smaller than eps
18+
(beta - 1) * log1p(-eps(typeof(x))) - logbeta(alpha, beta) :
19+
((x == 1 && beta <= 1) ? #Special case to avoid infinite PDF at 1
20+
(alpha - 1) * log1p(-eps(typeof(x))) -
21+
beta + 1 + #as if we were using 1-x=(eps / e)
22+
(beta - 1) * log(eps(typeof(x))) - logbeta(alpha, beta) :
23+
(alpha - 1) * log(x) + (beta - 1) * log1p(-x) - logbeta(alpha, beta) )))
1624
end
1725

1826
function logpdf_grad(::Beta, x::Real, alpha::Real, beta::Real)

test/modeling_library/distributions.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ end
2424
# out of support
2525
@test logpdf(beta, -1, 0.5, 0.5) == -Inf
2626

27+
# avoid infinities, sanely
28+
@test logpdf(beta, eps(typeof(0.)), 0.5, 0.5) < logpdf(beta, 0., 0.5, 0.5) < Inf
29+
@test logpdf(beta, eps(typeof(0.)), 0.5, 1.5) < logpdf(beta, 0., 0.5, 1.5) < Inf
30+
@test logpdf(beta, 1-eps(typeof(0.)), 0.5, 0.5) < logpdf(beta, 1., 0.5, 0.5) < Inf
31+
@test logpdf(beta, 1-eps(typeof(0.)), 1.5, 0.5) < logpdf(beta, 1., 1.5, 0.5) < Inf
32+
2733
# logpdf_grad
2834
f = (x, alpha, beta_param) -> logpdf(beta, x, alpha, beta_param)
2935
args = (0.4, 0.2, 0.3)

0 commit comments

Comments
 (0)