Skip to content

Instantly share code, notes, and snippets.

@mbillingr
Last active February 13, 2018 08:22
Show Gist options
  • Save mbillingr/bf6026d39f719f3d42e882df5c40c49a to your computer and use it in GitHub Desktop.
Save mbillingr/bf6026d39f719f3d42e882df5c40c49a to your computer and use it in GitHub Desktop.
Confidence Interval of the Median
import numpy as np
import scipy.stats as sps
def median_ci(x, alpha=0.95, method='approximate'):
"""confidence interval of the median"""
n = len(x)
y = np.sort(x)
if method[0] == 'a':
i = sps.norm.ppf(0.5-alpha/2) * np.sqrt(0.25*n) + 0.5 * n
a = int(np.floor(i))
b = int(np.ceil(i))
f = i - a
cl = y[a] + (y[b] - y[a]) * f
cu = y[n-1-b] + (y[n-1-a] - y[n-1-b]) * (1 - f)
p_final = alpha
else:
p = sps.binom.cdf(np.arange(0, n), n, 0.5)
pc = p[::-1] - p
i = np.argmin(np.abs(pc-alpha))
cl, cu = y[i], y[n-i-1]
p_final = pc[i]
return cl, cu, p_final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment