"""Mock-only independent binomial simulation and exact reference. Standard library."""
import json
import math
import random

def reference(n, p, target):
    mass = [math.comb(n, k) * p**k * (1-p)**(n-k) for k in range(n+1)]
    def quantile(q):
        cumulative = 0
        for k, value in enumerate(mass):
            cumulative += value
            if cumulative >= q - 1e-14:
                return k
    threshold = math.ceil(n * target - 1e-10)
    return dict(low=quantile(.025), high=quantile(.975), probability=sum(mass[threshold:]))

if __name__ == '__main__':
    rng = random.Random(2)
    draws = sorted(sum(rng.random() < .68 for _ in range(300)) for _ in range(20000))
    print(json.dumps(dict(exact=reference(300, .68, .68), simulation=[draws[499], draws[19499]])))
