import math
def get_confidence_interval(p, n, alpha=0.5):
assert p >= 0 and p <= 1
assert alpha > 0 and alpha < 1
z = pnorm(1-alpha/2)
return (p + (math.pow(z, 2)/(2*n)) - z * math.sqrt((p * (1 - p) + (math.pow(z, 2)/(4*n)))/n))
pnorm_table = [1.570796288, 0.03706987906, -0.8364353589e-3,
-0.2250947176e-3, 0.6841218299e-5, 0.5824238515e-5,
-0.104527497e-5, 0.8360937017e-7, -0.3231081277e-8,
0.3657763036e-10, 0.6936233982e-12]
def pnorm(qn):
assert qn >= 0.0 and qn <= 1.0, "Error : qn <= 0 or qn >= 1 in pnorm()!\n"
if(qn == 0.5):
return 0.0
w1 = qn
if(qn > 0.5):
w1 = 1.0 - w1
w3 = 0 - math.log(4.0 * w1 * (1.0 - w1))
w1 = pnorm_table[0]
for i in range(1, 11):
w1 += pnorm_table[i] * math.pow(w3, i);
if(qn > 0.5):
return math.sqrt(w1 * w3)
return 0 - math.sqrt(w1 * w3)