Skip to content

Instantly share code, notes, and snippets.

@grinnbearit
Last active September 20, 2021 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grinnbearit/e52f740c9220903169a0 to your computer and use it in GitHub Desktop.
Save grinnbearit/e52f740c9220903169a0 to your computer and use it in GitHub Desktop.
Credible interval of 1 dimensional distributions in Python
def credible_interval(xlim, ys, mass=0.95):
"""Given a range, like (0, 20), and the y values for the probability density function,
returns the set of intervals spanning the minimum range to sum up to the mass."""
indexed = zip(ys, range(len(ys)))
indexed.sort(reverse=True)
acc = 0
points = []
for (y, x) in indexed:
if acc + y > mass:
break;
acc += y
points.append(x)
points.sort()
sections = []
section = [points[0], points[0]]
for point in points[1:]:
if section[1] != (point - 1):
sections.append(section)
section = (point, point)
else:
section[1] = point
sections.append(section)
xs = np.linspace(xlim[0], xlim[1], len(ys))
translated = [(xs[lb], xs[ub]) for (lb, ub) in sections]
return translated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment