💻 Module: 02-Control-Flow • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb)

Lesson 09: while Loops, Bisection Solvers & Iterative Environmental Equilibrium

The “Boring Stuff” Problem: Nonlinear Equations You Cannot Rearrange by Hand

In algebra class, \(2x + 5 = 11\) solves neatly to \(x = 3\). In environmental engineering, almost every real design equation traps your unknown inside exponents, logarithms, or fractions on BOTH sides:

  1. Aqueous Chemistry: Finding equilibrium \(\text{pH}\) of rainwater exposed to atmospheric \(\text{CO}_2\) (\(420\text{ ppm}_v\)) balances \([\text{H}^+] = [\text{OH}^-] + [\text{HCO}_3^-] + 2[\text{CO}_3^{2-}]\), a cubic equation in \([\text{H}^+]\)!
  2. Environmental Hydraulics (Fluid Mechanics): Finding the Colebrook–White sewer pipe friction factor \(f\) where \(f\) sits inside both \(1/\sqrt{f}\) and \(\log_{10}(\dots/\sqrt{f})\).

A while loop acts like a patient bisection bracket: keep halving [low, high] until error falls below 1e-9—ALWAYS including a max_iter safety counter so a bug never locks your laptop in an infinite loop!

import math

# Example 1 (Water Chemistry): Bisection Solver for Natural Rainwater pH at P_CO2 = 420 ppmv (4.2e-4 atm)
# At 25 degC: K_H = 10^-1.47, K1 = 10^-6.35, K2 = 10^-10.33, Kw = 10^-14.0
P_CO2 = 4.2e-4
H2CO3_star = (10 ** -1.47) * P_CO2
K1, K2, Kw = 10 ** -6.35, 10 ** -10.33, 10 ** -14.0

def charge_residual(ph):
    H = 10.0 ** (-ph)
    OH = Kw / H
    HCO3 = K1 * H2CO3_star / H
    CO3 = K2 * HCO3 / H
    # Positive cations - negative anions (= 0 at equilibrium)
    return H - (OH + HCO3 + 2.0 * CO3)

lo, hi = 3.0, 9.0
iters = 0
while (hi - lo) > 1e-8 and iters < 80:
    mid = 0.5 * (lo + hi)
    if charge_residual(lo) * charge_residual(mid) <= 0.0:
        hi = mid
    else:
        lo = mid
    iters += 1

ph_rain = 0.5 * (lo + hi)
print(f"=== Atmospheric CO2 = 420 ppmv Rainwater Carbonate Equilibrium ===")
print(f"Converged in {iters} bisection steps -> Natural Rainwater pH = {ph_rain:.4f} (acidic, NOT 7.0!)")
print(f"Check Charge Residual = {charge_residual(ph_rain):.2e} eq/L")
=== Atmospheric CO2 = 420 ppmv Rainwater Carbonate Equilibrium ===
Converged in 30 bisection steps -> Natural Rainwater pH = 5.5980 (acidic, NOT 7.0!)
Check Charge Residual = 2.76e-14 eq/L
# Example 2 (Fluid Mechanics Sewer Line): Fixed-Point while Loop for Implicit Colebrook Friction Factor
Re_sewer = 3.2e5      # Gravity outfall Reynolds number [-]
eps_D = 0.0012        # Concrete pipe relative roughness (k_s / D)

f = 0.025             # Reasonable initial turbulent guess
err = 1.0
step = 0
while err > 1e-10 and step < 50:
    rhs = -2.0 * math.log10(eps_D / 3.7 + 2.51 / (Re_sewer * math.sqrt(f)))
    f_next = 1.0 / (rhs ** 2)
    err = abs(f_next - f)
    f = f_next
    step += 1

print("=== Implicit Colebrook Sewer Friction Solver ===")
print(f"Converged in {step} iterations: f = {f:.6f} (residual change = {err:.2e})")
=== Implicit Colebrook Sewer Friction Solver ===
Converged in 6 iterations: f = 0.021343 (residual change = 6.32e-12)

Concept Check Questions

  1. Why is natural unpolluted rainfall slightly acidic (\(\text{pH} \approx 5.6\)) instead of 7.0?
  2. What two conditions must lo and hi satisfy before running bisection (f(lo) * f(hi) <= 0)?
  3. Why should every engineering while loop combine tolerance (err > 1e-10) with a hard limit (and step < 100)?

Guided Practice Problem 1: Pre-Industrial vs. Modern Rainwater Acidity Shift

Re-run the carbonate bisection solver at pre-industrial \(\text{CO}_2\) (\(280\text{ ppm}_v\)) vs. elevated \(\text{CO}_2\) (\(560\text{ ppm}_v\)) and find the exact rainwater \(\Delta\text{pH}\) shift!

# Guided Practice 1 Starter
for label, ppm in [("Pre-industrial 280 ppm", 280e-6), ("Doubled 560 ppm", 560e-6)]:
    h2co3 = (10 ** -1.47) * ppm
    res_fn = lambda ph: 10**(-ph) - (1e-14/10**(-ph) + K1*h2co3/10**(-ph) + 2*K1*K2*h2co3/10**(-2*ph))
    a, b = 3.0, 9.0
    for _ in range(50):
        m = 0.5 * (a + b)
        a, b = (a, m) if res_fn(a) * res_fn(m) <= 0 else (m, b)
    print(f"{label:<24s}: pH = {0.5*(a+b):.4f}")
Pre-industrial 280 ppm  : pH = 5.6859
Doubled 560 ppm         : pH = 5.5356