Skip to content

Commit

Permalink
try to fix numerical instability with high values of the degrees of f…
Browse files Browse the repository at this point in the history
…reedom of the t-distribution
  • Loading branch information
FelixNoessler committed Apr 22, 2024
1 parent 5e866ba commit 0424b04
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/distrs/fdist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,17 @@ end
for f in ("invcdf", "invccdf", "invlogcdf", "invlogccdf")
ff = Symbol("fdist"*f)
bf = Symbol("beta"*f)
cf = Symbol("chisq"*f)
@eval function $ff(ν1::T, ν2::T, y::T) where {T<:Real}
x = $bf(ν1/2, ν2/2, y)
return x/(1 - x)*ν2/ν1
# the evaluation of the CDF with the t-distribution combined with the
# beta distribution is unstable for high ν2,
# therefore, we switch from the beta to the chi-squared distribution at ν > 1.0e7
if ν2 > 1.0e7
return $cf(ν1, y)/ν1
else
x = $bf(ν1/2, ν2/2, y)
return x/(1 - x)*ν2/ν1
end
end
@eval $ff(ν1::Real, ν2::Real, y::Real) = $ff(promote(ν1, ν2, y)...)
end
4 changes: 3 additions & 1 deletion src/distrs/tdist.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ tdistpdf(ν::Real, x::Real) = exp(tdistlogpdf(ν, x))

tdistlogpdf::Real, x::Real) = tdistlogpdf(promote(ν, x)...)
function tdistlogpdf::T, x::T) where {T<:Real}
isinf(ν) && return normlogpdf(x)
# the logpdf equation of the t-distribution is numerically unstable for high ν,
# therefore we switch at ν > 1.0e7 to the normal distribution
ν > 1.0e7 && return normlogpdf(x)
νp12 =+ 1) / 2
return loggamma(νp12) - (logπ + log(ν)) / 2 - loggamma/ 2) - νp12 * log1p(x^2 / ν)
end
Expand Down

0 comments on commit 0424b04

Please sign in to comment.