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

Lesson 06: while Loops, Convergence Criteria & Hand-Built Nonlinear Solvers

The “Boring Stuff” Problem: Implicit Engineering Equations You Cannot Isolate

Look at the famous Colebrook–White Equation from Fluid Mechanics Module 5: \[\frac{1}{\sqrt{f}} = -2.0 \log_{10}\left(\frac{\varepsilon/D}{3.7} + \frac{2.51}{\text{Re}_D\sqrt{f}}\right)\] Notice friction factor \(f\) sits trapped on both sides inside a square root and a base-10 logarithm! There is NO closed-form algebraic formula \(f = \dots\) you can type once on a calculator. In the old days, engineers squinted at a tiny printed Moody chart.

With a Python while loop, you simply guess \(f_0 = 0.02\), plug it into the right-hand side to get a sharper estimate \(f_1\), and keep looping while the change \(|f_{\text{new}} - f_{\text{old}}| > 10^{-8}\)! In 5–7 automatic passes (less than 0.05 milliseconds), Python nails \(f\) to 8+ significant figures.


How while Differs from for (Plus the Golden Infinite-Loop Guard!)

A for loop runs for a known count (24 hours, 5 diameters). A while loop repeats as long as a condition stays True—making it ideal for convergence solvers, tank draining simulation, and input validation.

Watch Out! Two Golden Rules to Never Freeze Your Notebook

  1. Always Include a max_iter Counter: Even if an equation diverges or has a typo, while err > tol and iters < max_iter: prevents an infinite loop from locking up your computer!
  2. Always Update the Loop Variable Inside the Body: Before writing while ..., ask yourself: “What single line inside this loop guarantees the condition eventually flips False?”
import math

# Example 1 (Fluid Mechanics Module 5): Fixed-Point Colebrook-White Darcy Friction Solver
Re_D = 2.5e5
eps_D = 0.0005  # Commercial steel roughness ratio (epsilon / D)

# Seed with explicit Haaland approximation for ultra-fast convergence
f = (-1.8 * math.log10((eps_D / 3.7) ** 1.11 + 6.9 / Re_D)) ** -2
tol = 1e-10
err = 1.0
iters = 0
max_iter = 50

print("Iter | Friction Factor f | Change |f_new - f_old|")
print("-" * 52)
while err > tol and iters < max_iter:
    iters += 1
    rhs = -2.0 * math.log10((eps_D / 3.7) + (2.51 / (Re_D * math.sqrt(f))))
    f_new = 1.0 / (rhs ** 2)
    err = abs(f_new - f)
    f = f_new
    print(f"{iters:4d} | {f:17.10f} | {err:.2e}")

print(f"\nConverged to f = {f:.8f} in {iters} iterations!")
Iter | Friction Factor f | Change |f_new - f_old|
----------------------------------------------------
   1 |      0.0184691207 | 1.63e-04
   2 |      0.0184622643 | 6.86e-06
   3 |      0.0184625503 | 2.86e-07
   4 |      0.0184625384 | 1.19e-08
   5 |      0.0184625389 | 4.98e-10
   6 |      0.0184625389 | 2.08e-11

Converged to f = 0.01846254 in 6 iterations!
# Example 2 (Heat Transfer Module 7): Newton-Raphson Solver for Combined Convection + Radiation Surface T_s
# Balance: q_flux_elec = h * (T_s - T_air) + eps * sigma * (T_s^4 - T_surr^4)
# Solve g(T_s) = h*(T_s - T_air) + eps*sigma*(T_s^4 - T_surr^4) - q_flux = 0

q_flux = 6500.0          # Chip power flux [W/m^2]
h = 35.0                 # Air convection [W/(m^2*K)]
T_air = 298.15           # 25 degC [K]
T_surr = 298.15          # Walls at 25 degC [K]
eps = 0.85               # Emissivity [-]
sigma = 5.670374419e-8

T_s = 400.0              # Initial Kelvin guess
iters = 0
step = 1.0

while abs(step) > 1e-7 and iters < 40:
    iters += 1
    g_val = h * (T_s - T_air) + eps * sigma * (T_s**4 - T_surr**4) - q_flux
    dg_dT = h + 4.0 * eps * sigma * (T_s ** 3)  # Exact analytical derivative!
    step = g_val / dg_dT
    T_s -= step

print("=== Newton-Raphson Combined Convection + Radiation Solver ===")
print(f"Iterations  : {iters}")
print(f"Surface T_s : {T_s:.4f} K ({T_s - 273.15:.2f} degC)")
# Verify residual balance:
residual = h * (T_s - T_air) + eps * sigma * (T_s**4 - T_surr**4) - q_flux
print(f"Energy Check: residual = {residual:.2e} W/m^2")
=== Newton-Raphson Combined Convection + Radiation Solver ===
Iterations  : 4
Surface T_s : 442.1264 K (168.98 degC)
Energy Check: residual = 0.00e+00 W/m^2

Practice Questions (Concept Check)

  1. What happens if you forget iters += 1 inside a while err > tol and iters < max_iter: loop whose equation fails to converge?
  2. Why does Fixed-Point Iteration converge on Colebrook–White in only ~3 iterations when seeded with Haaland’s formula?
  3. What extra mathematical piece does Newton–Raphson require compared to the Bisection Method, and why is Newton–Raphson much faster when it works?
  4. When simulating a draining water tank while height > 0.05:, why might subtracting dh without checking if height <= 0: overshoot slightly negative?

Guided Practice Problem 1 (Worked Self-Check): Unsteady Cylindrical Tank Draining Time (Fluid Mechanics)

A vertical cylindrical tank of diameter \(D_t = 1.20\text{ m}\) holds water up to \(h_0 = 2.00\text{ m}\) and drains out a bottom orifice of diameter \(d_o = 40\text{ mm}\) (\(C_d = 0.61\)). Using Torricelli’s law \(\frac{dh}{dt} = -C_d \left(\frac{d_o}{D_t}\right)^2 \sqrt{2gh}\), step time forward with Euler steps \(\Delta t = 1.0\text{ s}\) using a while loop until depth drops below \(h_{\text{final}} = 0.20\text{ m}\). Compare your loop time to the exact analytical draining time: \[t_{\text{exact}} = \frac{2\left(\sqrt{h_0} - \sqrt{h_{\text{final}}}\right)}{C_d (d_o / D_t)^2 \sqrt{2g}}\]

Hint: Track t = 0.0 and h = h0 before the loop

Inside while h > h_final:, compute dh_dt, update h += dh_dt * dt, and increment t += dt.

# Worked Practice Problem 1 Solution: While-Loop Tank Draining Simulation
D_t, d_o, C_d, g = 1.20, 0.040, 0.61, 9.81
h, h_final = 2.00, 0.20
dt = 1.0
t = 0.0
coeff = C_d * ((d_o / D_t) ** 2) * math.sqrt(2.0 * g)

while h > h_final and t < 50000:
    dh_dt = -coeff * math.sqrt(h)
    h += dh_dt * dt
    t += dt

t_exact = (2.0 * (math.sqrt(2.00) - math.sqrt(0.20))) / coeff
print(f"While-Loop Time (dt=1 s) : {t:.1f} s ({t/60:.2f} min)")
print(f"Exact Analytical Time    : {t_exact:.1f} s ({t_exact/60:.2f} min)")
print(f"Relative Error           : {abs(t - t_exact)/t_exact:.3%}")
While-Loop Time (dt=1 s) : 644.0 s (10.73 min)
Exact Analytical Time    : 644.2 s (10.74 min)
Relative Error           : 0.031%

End-of-Chapter Practice Problems (Try Yourself!)

  1. Bisection Solver for Pipe Diameter Sizing (Fluid Mechanics Type III): Using while (D_hi - D_lo) > 1e-6:, find the exact pipe diameter \(D \in [0.05, 0.40]\text{ m}\) needed to deliver \(Q = 0.035\text{ m}^3/\text{s}\) of water over \(L = 250\text{ m}\) with fixed friction factor \(f = 0.022\) and allowable head loss \(h_f = 12.0\text{ m}\) (\(h_f = \frac{8 f L Q^2}{\pi^2 g D^5}\)).
  2. Compounded Fatigue Miner’s Damage Counter (Solid Mechanics): Repeated thermal-pressure cycles inflict damage \(10^{-4}\) each at full load. Use a while loop simulating random occasional overstress peaks (1.5e-4 every 5th cycle using cycle % 5 == 0) to count how many cycles remain before Palmgren–Miner damage sum \(D_{\text{cum}} \ge 1.0\).
  3. Adiabatic Cooling Iteration (Heat Transfer): Find how many minutes a \(T_0 = 650^\circ\text{C}\) steel billet cools with Euler \(\Delta t = 5\text{ s}\) under lumped convection (\(\tau = 280\text{ s}\), \(T_\infty = 30^\circ\text{C}\)) before reaching safe handling temperature \(T \le 60^\circ\text{C}\).

🎬 Concept & Engineering Animation

🎬 Colebrook While Convergence