Applications of Loops
Engineering Loop Applications
Engineering programs rarely loop just to loop. A loop earns its place when the same small calculation must be repeated many times: adding up thousands of sensor readings, advancing a simulation one time step at a time, or refining a guess until a design equation is satisfied. These three jobs (accumulate, step, converge) cover many loops in engineering computing. Each has a typical structure and a typical bug; recognizing the pattern helps you choose the loop and its stopping rule.
Accumulating totals and integrals
An accumulator is a variable initialized once before the loop and updated on every pass, so that after the loop it holds the combined result. Totals of energy, mass or cost from logged data use this pattern, and so does numerical integration. The trapezoidal rule splits [a,b] into n sub-intervals of width h and adds the area of one trapezoid per pass:
def trapezoid(f, a, b, n):
h = (b - a) / n
total = 0.0 # accumulator, set once
for i in range(n):
x_left = a + i * h # coordinate from the index
total += 0.5 * h * (f(x_left) + f(x_left + h))
return totalHere n must be a positive integer. The number of passes is known before the loop starts, so a for loop over range(n) is the natural choice. Computing xi from the integer index, rather than repeatedly adding h, avoids cumulative rounding drift in the coordinate.
Time stepping a physical state
Many engineering models give a rate of change, dy/dt=f(t,y), rather than y itself. A time-stepping loop advances a known initial value. Explicit (forward) Euler uses the rate at the start of each step:
For this fixed-step implementation, assume time starts at zero, Δt>0, tend≥0, and tend/Δt is an integer.
# Requires t_end / dt to be mathematically an integer.
n_steps = round(t_end / dt)
y = y0
for k in range(n_steps):
t = k * dt
y = y + dt * f(t, y)Rounding converts the assumed integer ratio to a step count despite floating-point representation error; it does not make arbitrary ratios valid. For example, tend=1 s and Δt=0.3 s violate the assumption: three steps reach only 0.9 s. Choose a step that divides the interval or implement a shorter final step.
The code retains only the current state; append values to a list for a history. Under the stated assumptions, reaching tend takes nsteps=tend/Δt steps. Storing the initial value and every updated value gives nsteps+1 points. Confusing these counts causes off-by-one errors. For a sufficiently smooth model and a stable, sufficiently small Euler step, halving Δt roughly halves the error at a fixed end time, while doubling the work.
Iterating until converged
Nonlinear design equations often require repeatedly refining a guess. A convergence criterion specifies when to accept an iterate, commonly when successive values differ by less than a positive tolerance:
Newton's method uses xk+1=xk−f(xk)/f′(xk). Assuming a usable, nonzero derivative and a positive integer iteration cap:
x, k = x0, 0
while True:
x_new = x - f(x) / dfdx(x)
change = abs(x_new - x)
x = x_new # retain the accepted iterate
k += 1
if change < tol:
break
if k >= max_iter:
raise RuntimeError('Newton iteration did not converge')This loop tests convergence after each update. Successful termination depends on the criterion, since the required number of passes is unknown. Exact equality is generally unsuitable as the sole test for reaching an inexact numerical target. However, x_new == x can detect stagnation, and equality comparisons are valid for exactly representable values. A small change does not prove the equation is satisfied; check the residual f(x) too when accuracy matters.
Pattern | Usual loop | Passes known in advance? | Stop rule | Engineering example |
|---|---|---|---|---|
Accumulation | for over data or sub-intervals | Yes | Data or sub-intervals exhausted | Energy from a power log |
Time stepping | for over steps | Yes, integer tend/Δt when starting at zero | Prescribed step count completed | Cooling of a component |
Convergence | while with an iteration cap | No | Criterion met; otherwise report failure at the cap | Root of a design equation |
What to remember
- Identify whether the loop accumulates, time-steps or converges.
- Initialize an accumulator once, before the loop.
- For fixed counts, compute coordinates and times from the integer index to avoid cumulative rounding drift.
- Starting at zero, fixed-step simulation takes tend/Δt steps only when this ratio is an integer; a complete history includes one extra initial point.
- Retain the accepted iterate before exiting a convergence loop. Use a suitable tolerance and an iteration cap; exact equality alone generally cannot establish numerical accuracy.
Example: Cooling a power transistor with a time-stepping loop
A power transistor is switched off at t=0 with its case at 90 ∘C. Its heat sink sits in still air at 20 ∘C, and lab tests show the case temperature follows Newton's law of cooling:
A technician simulates the cooldown with forward Euler and a time step of Δt=2.0 s:
k, T_env, dt = 0.05, 20.0, 2.0 # 1/s, degC, s
T = 90.0 # degC at t = 0
for step in range(n_steps):
T = T + dt * (-k * (T - T_env))a) Trace the loop by hand for its first two passes. What temperatures does it compute for t=2.0 s and t=4.0 s?
Each pass evaluates the cooling rate at the current temperature, multiplies it by Δt, and adds the result to T.
The loop reports 83.0 ∘C at 2.0 s and 76.7 ∘C at 4.0 s. The second drop is smaller than the first because the rate depends on the temperature difference, which the first pass has already reduced.
b) What value of n_steps simulates the first 60 s? Find the temperature the loop reports at t=60 s without tracing every pass, and compare it with the exact solution T(t)=Tenv+(T0−Tenv)e−kt.
The number of steps is 60 s/2.0 s=30, so n_steps = 30. Those 30 passes produce T1 through T30; with the initial value that is ________ temperatures, the usual one-more-point-than-steps count.
Subtract Tenv from both sides of the update to see what each pass does to the temperature difference. Use j as the iteration index, keeping k for the cooling constant:
Every pass multiplies the difference by ________, so after n passes Tn=20+70(0.9)n. For n=30:
The exact solution gives
The loop is 0.52 ∘C low. Forward Euler uses the rate at the start of each step, which is the fastest cooling rate within that step, so every step overestimates the drop. As a check on the first-order behaviour: with Δt=1.0 s the loop would give 20+70(0.95)60≈23.22 ∘C, an error of 0.26 ∘C, about half the original.
c) The technician now wants the loop to stop at the first step where the case temperature is below 30 ∘C, without knowing the step count in advance. Describe the while loop, then find how many passes it makes and the simulated time at which it stops.
The count is now unknown, so the stop test must drive the loop and a counter must record the passes:
- Before the loop: T = 90.0 and steps = 0.
- Loop header: while T >= 30.0: so the body runs as long as the target has not been reached.
- Body: the same update T = T + dt * (-k * (T - T_env)), then steps += 1.
- After the loop: the stopping time is steps * dt, computed from the integer counter.
Using Tn=20+70(0.9)n, the loop stops at the first n with 70(0.9)n<10, that is (0.9)n<1/7:
Check the two candidates. After 18 passes, T18=20+70(0.9)18≈30.51 ∘C, still at or above 30, so the loop continues. After 19 passes, T19=20+70(0.9)19≈29.46 ∘C, so the condition fails and the loop exits.
The loop makes 19 passes and stops at t=19×2.0=38 s. The exact temperature reaches 30 ∘C at t=ln7/0.05≈38.92 s. Euler's cooling bias makes the numerical threshold crossing occur too early. Checking only at whole-step endpoints delays detection until the next endpoint, partly offsetting that bias. The reported stopping time of 38 s is still earlier than the exact crossing.
A vehicle test logs speed every 2.0 s. The following loop estimates the distance travelled with the trapezoidal rule:
t = [0.0, 2.0, 4.0, 6.0, 8.0] # s
v = [0.0, 4.0, 7.5, 10.0, 11.5] # m/s
distance = 0.0
for i in range(len(t) - 1):
distance += 0.5 * (t[i+1] - t[i]) * (v[i] + v[i+1])What value of distance does the loop compute? Give your answer in m, to one decimal place.
A bisection loop locates the water depth at which a channel carries its design flow. The root is bracketed in [1.0,3.0] m. Each pass of the loop halves the bracket, and the loop stops as soon as the bracket width is at most 1.0×10−3 m.
How many passes does the loop make?