A48 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 8 · Loops

Let the computer do it a million times

Most of what makes code worth writing is repetition: step a simulation through ten thousand time steps, add up a series until it settles, try every resistor in a range, refine an estimate until it stops changing. Python has two loops. for repeats a known number of times; while repeats until a condition changes. Between them they cover every kind of repetition a numerical method needs.

Predict

What does this print?

total = 0
for k in range(1, 5):
    total += k
print(total)

Name it

for loops

for k in range(n):        # k = 0, 1, ..., n-1
    ...
for k in range(a, b):     # k = a, ..., b-1
for k in range(a, b, s):  # in steps of s

The accumulator pattern builds a result across the loop:

total = 0
for k in range(n):
    total += term(k)

and so does tracking the best so far:

best = None
for x in candidates:
    if best is None or score(x) > score(best):
        best = x

while loops

while condition: repeats as long as the condition is true. Use it when you don't know in advance how many steps you'll need:

n = 0
while 2**n < M:      # smallest n with 2**n >= M
    n += 1

Make sure the loop ends. Something in the body has to move the condition toward false. A safety limit is cheap insurance:

for _ in range(10000):
    ...
    if converged:
        break

break leaves a loop early; continue skips to the next pass.

Iterating to a fixed point

Many numerical methods repeat a formula until the answer stops changing. To find a, start anywhere and repeat x←12(x+a/x):

x = a
while abs(x * x - a) > 1e-12 * a:
    x = 0.5 * (x + a / x)

Each pass roughly doubles the number of correct digits. This is Newton's method (A6 and lesson 37), and the pattern of "update, test, repeat" is the same for every iterative solver.

Worked example

Add up 1+12+14+⋯ until the next term is below 10−9.

Show the solution
  1. Loop while the term is big enough. Add the term, then halve it.
total, term = 0.0, 1.0
while term >= 1e-9:
    total += term
    term /= 2
print(total)      # 1.9999999981373549
  1. Count the terms. The loop stops after 30 terms.
  2. Check against the formula. The sum is within 2×10−9 of the exact 2 from A2's geometric series formula, which is a good check that the loop is right.

Answer 30 terms add up to 1.9999999981, within 2×10−9 of the exact 2.

Worked example

A capacitor charges as v=1−e−t/τ. Stepping t in units of 0.1τ, after how many steps is it above 0.99?

Show the solution
  1. Step until the voltage passes 0.99. Count steps of 0.1τ in a while loop.
import math
k = 0
while 1 - math.exp(-k * 0.1) <= 0.99:
    k += 1
print(k, k * 0.1)     # 47 4.7
  1. Read the result. 47 steps, 4.7τ.
  2. Check against the exact crossing. It is at t=τln⁡100=4.605τ and the loop reports the first step past it.

Answer after 47 steps, at 4.7τ.

Check

A ladder has n = 15 resistors in series: the first is R0 = 100 Ω and each one after is d = 10 Ω bigger. Set total to their sum, using a for loop.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Using a while loop, set n to the smallest whole number with 2n≥ M = 1000.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Find a for a = 10 by repeating x←12(x+a/x) from x=a until |x2−a|≤10−12a. Set x to the result and steps to how many updates it took.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

A capacitor charges as 1−e−k⋅0.1 after k steps of 0.1τ. Set k to the first step at which it exceeds f = 0.95.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

An RC low-pass driven by a 1 V step obeys vk+1=vk+r(1−vk) when stepped forward by Euler's method, with r=Δt/τ. Starting from v=0, run n = 50 steps with r = 0.1 in a for loop. Set v to the final value and err to how far it is from the exact 1−e−nr.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

How many times does the body of for k in range(2, 11, 3): run?

Explain why

When would you use while instead of for?

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.