15/32
Part 4 of 6 · The worked exampleLearn
The whole function splits into two branches after the rates
Every piece so far fits in one function. After the rates, it splits into two branches, each with its own standard error.
| Branch | The rate it uses | Then |
|---|---|---|
| the test | one pooled rate for everyone | the pooled SE, then z, then p_value |
| the interval | each group keeps its own rate | the unpooled SE, then ci |
Both branches start from the two rates and diff, B's rate minus A's. This is levels 1 to 3 of the practice. Level 4 adds the split check from the first chapter as one more key, srm.
from math import sqrt
from statistics import NormalDist
def two_proportion_test(conv_a, n_a, conv_b, n_b, alpha=0.05):
pa, pb = conv_a / n_a, conv_b / n_b
diff = pb - pa
# the null's one rate
pooled = (conv_a + conv_b) / (n_a + n_b)
z = diff / sqrt(pooled * (1 - pooled) * (1 / n_a + 1 / n_b))
# both tails
p_value = 2 * (1 - NormalDist().cdf(abs(z)))
se = sqrt(pa * (1 - pa) / n_a + pb * (1 - pb) / n_b)
half = NormalDist().inv_cdf(1 - alpha / 2) * se
return {"diff": diff, "z": z, "p_value": p_value,
"ci": (diff - half, diff + half)}
for counts in [(200, 2000, 250, 2000), (250, 2000, 200, 2000),
(100, 1000, 100, 1000)]:
r = two_proportion_test(*counts)
low, high = r["ci"]
print(f"z {r['z']:+.4f} p {r['p_value']:.5f} "
f"ci {low:+.5f} to {high:+.5f}")
The second run swaps the groups: 250 of 2,000 against 200 of 2,000. What happens to z and p?
Pick one to see what it prints.
Pick an answer above to see the rest