Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: quantiles and confidence intervals

Tags:

julia

Does Julia have a function to calculate the density points where p% of the distribution is included?

Something like the scipy.stats norm.ppf function mentioned in this answer

Example: 2-sided 95% confidence interval:

> norm.ppf(1-(1-0.95)/2)
1.96

> norm.ppf(1-(1+0.95)/2)
-1.96
like image 465
PatrickT Avatar asked Jan 03 '23 22:01

PatrickT


1 Answers

Just to add another related enhancement to the answer, especially for users of Bayesian posteriors, we can define medianinterval as follows:

medianinterval(d,p = 0.95) = quantile(d,1-(1+p)/2),quantile(d,(1+p)/2)

and have:

julia> medianinterval(Normal())
(-1.9599639845400576, 1.9599639845400576)

But sometimes a more efficient (i.e. shorter) interval will be around the mode of the distribution. To address this we can define:

function modeinterval(d,p=0.95)
    mcdf = cdf(d,mode(d))
    endpoints = mcdf < p/2 ? (0,p) : mcdf > 1-p/2 ? (1-p,1) : (mcdf-p/2,mcdf+p/2)
    return map(x->quantile(d,x), endpoints)
end

For the Normal distribution it doesn't matter since the mode is also the median, but for other distributions such as the Beta, we can have:

julia> modeinterval(Beta(2,8),0.2)
(0.09639068616673087, 0.15355172436770012)

julia> medianinterval(Beta(2,8),0.2)
(0.1498495815725847, 0.21227857915644155)

julia> 0.15355172436770012 - 0.09639068616673087
0.05716103820096925

julia> 0.21227857915644155 - 0.1498495815725847
0.06242899758385684

The mode interval covers the same fraction of the distribution with a shorter length. See Credible interval for related discussion.

like image 196
Dan Getz Avatar answered Feb 23 '23 08:02

Dan Getz