#!/usr/bin/env python3
# Source: t2-statistics.html
import random, statistics as st

rng = random.Random(7)
a = [rng.expovariate(1 / 10.0) for _ in range(200)]   # control
b = [rng.expovariate(1 / 12.5) for _ in range(200)]   # treatment
obs = st.mean(b) - st.mean(a)

# Permutation test: shuffle labels under H0 (no difference).
pool, n, B = a + b, len(a), 5000
extreme = 0
for _ in range(B):
    rng.shuffle(pool)
    d = st.mean(pool[n:]) - st.mean(pool[:n])
    extreme += abs(d) >= abs(obs)
p_perm = (extreme + 1) / (B + 1)

# Percentile bootstrap CI for the difference in means.
boots = []
for _ in range(B):
    ra = [rng.choice(a) for _ in a]
    rb = [rng.choice(b) for _ in b]
    boots.append(st.mean(rb) - st.mean(ra))
boots.sort()
lo, hi = boots[int(0.025 * B)], boots[int(0.975 * B) - 1]

print(f"observed diff = {obs:.2f}")
print(f"permutation p = {p_perm:.4f}")
print(f"95% bootstrap CI = ({lo:.2f}, {hi:.2f})")
