Last active
February 13, 2018 08:22
-
-
Save mbillingr/bf6026d39f719f3d42e882df5c40c49a to your computer and use it in GitHub Desktop.
Confidence Interval of the Median
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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