"""Lab to Code — Bread from air: how pressure pushes the Haber-Bosch equilibrium (ideal-gas estimate).

N2 + 3 H2 <-> 2 NH3, fed 1 : 3. Kp = 1.45e-5 atm^-2 at 500 C (textbook value).
"""
KP_500C = 1.45e-5   # atm^-2


def ammonia_share(P, Kp=KP_500C):
    """Mole fraction of NH3 at equilibrium, total pressure P in atm (bisection on the extent)."""
    def gap(z):                       # z = mol of N2 that reacted, starting from 1 N2 + 3 H2
        n = 4 - 2 * z
        y_n2, y_h2, y_nh3 = (1 - z) / n, (3 - 3 * z) / n, 2 * z / n
        return y_nh3**2 / (y_n2 * y_h2**3 * P**2) - Kp
    lo, hi = 0.0, 0.999999
    for _ in range(60):
        mid = (lo + hi) / 2
        lo, hi = (lo, mid) if gap(mid) > 0 else (mid, hi)
    z = (lo + hi) / 2
    return 2 * z / (4 - 2 * z)


for P in (1, 100, 200, 300):
    print(f"{P:>3} atm: {100 * ammonia_share(P):.1f}% ammonia")
