Engineering Programming With Python
From a sensor log to a simulation: decompose, compute, decide, loop, test, structure, search and solve
Eight chapters of Python written the way engineers use it: to check a battery budget, summarise a sensor log, test a safety rule at its edges, organise a program into modules and objects, choose the right data structure, measure an algorithm's cost, find a root and simulate a system changing in time. Every chapter ends with a program worth keeping.
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
1. Algorithms before code
The hardest part of a program is usually done before typing. Break the machine's job into steps a computer could follow, draw the decisions and loops as a flowchart, and list every combination of inputs in a rule table so no case is forgotten. Then write the first small program, a battery run-time calculator, and watch Python follow your steps exactly, including the wrong ones.
Figure 1.1. 3 inputs, 8 cases, check every one (described in words)
A rule table for three on/off inputs, hot, fan and door, listing all 8 combinations. The rule alarm = hot and not fan is true in 2 rows, which are highlighted: hot 1, fan 0, with door either 0 or 1.
Explanation
1.1 Break a machine's job into steps
A watering robot is told to 'look after the seedlings'. What exactly should it do at 07:00 tomorrow?
Decomposition: one big job, several small ones
'Look after the seedlings' is too big to solve in one go. Split it: sense (read moisture), decide (is it too dry?), act (open and close a valve), record (write a log line). Each piece is small enough to design, test and fix on its own, and different people can work on different pieces.
An algorithm is a precise recipe
An algorithm is a finite list of steps that solves one of those small jobs. Every step must be unambiguous: two people, or a computer, would do exactly the same thing. That usually means naming a quantity and a unit (35 % moisture, 60 s), and saying what happens next.
Every algorithm needs inputs, outputs and an end
Ask three questions of any algorithm. What does it read (inputs)? What does it produce (outputs)? How does it stop? A watering step without a stopping rule floods the tray. Good stopping rules often have a backup, such as 'or 60 s have passed', in case a sensor fails.
Common mix-ups
An algorithm has to be written in a programming language.
✓ An algorithm is the method. It can be numbered steps, a flowchart or code; code is just one way to write it down.If a person understands the steps, a computer will too.
✓ People fill gaps with common sense. Computers need every quantity, unit and stopping rule spelled out.
1.2 Flowcharts: drawing decisions and loops
A tank controller checks 'is the level equal to 90 L?' after each pump pass. Why might the tank overflow?
Three shapes are enough
Rounded boxes mark start and end. Rectangles are actions (pump on for one pass). Diamonds are decisions with exactly two exits, yes and no. Arrows say what happens next. An arrow that leads back up to an earlier decision makes a loop.
Trace tables catch bugs on paper
A trace table has one row each time you reach the decision: the value of every variable and whether the test is true. Tracing 20, 35, 50, 65, 80, 95 by hand shows exactly when the loop stops, before any pump is wired up.
Stop on a range, not an exact value
Real quantities rarely land exactly on a target. Steps of 15 L skip over 90 L; a sensor reading of 89.97 is not 90. A stopping test such as level < 90 (keep going while below) always ends; level != 90 can run for ever. Engineers also add a safety limit, such as a maximum number of passes or a high-level float switch.
Derivation: How many passes does the loop need?
The loop runs while
level < target. Start level S, each pass adds A litres.After n passes the level is S + n·A. The loop stops at the first n where S + n·A ≥ target.
Rearrange: n·A ≥ target − S, so n ≥ (target − S) / A.
n must be a whole number of passes, so n is (target − S) / A rounded up. From 20 L with A = 15 L and target 90 L: (90 − 20) / 15 = 4.67 → 5 passes, finishing at 20 + 5 × 15 = 95 L.
If S is already ≥ target, the condition is false at the first check and the pump runs 0 times.
Common mix-ups
If a loop condition looks sensible, the loop must end.
✓ Only trace tables, or reasoning about how the variable changes, show that it ends. Exact-match tests are a classic trap.Flowcharts are only for beginners.
✓ Engineers still sketch flowcharts and state diagrams to agree on logic before writing safety-critical code.
1.3 Trace every case with a rule table
A sorting machine reads three yes/no sensors. How many situations must its rules cover, and what happens in the one you forgot?
Count the cases first
With k yes/no inputs there are 2^k combinations: 2, 4, 8, 16, … An input with m settings (a selector switch) multiplies the count by m. Counting tells you how many rows a complete rule table, or a complete set of tests, needs.
A rule table is an algorithm
Each row says: for this combination of inputs, do this. Because the rows cover every combination, there is no situation in which the machine has to guess. A rule table is also the easiest way to show a client exactly what the machine will do.
Trace the strange cases
Bugs hide in combinations nobody pictured: a part that is red and metal, a sensor that says large and small at once. Pick the oddest inputs and trace the algorithm by hand. If you cannot say what it does, the algorithm is incomplete.
Common mix-ups
Testing the usual cases proves an algorithm works.
✓ Usual cases are where it was designed to work. Proof comes from covering every case, or at least the strange and boundary ones.
1.4 Your first Python program: battery runtime
Your sensor node has a 2000 mAh battery and draws 250 mA. Can six lines of Python tell you when it dies?
The program
# Battery runtime for a sensor node
capacity_mah = 2000 # battery capacity in mAh
current_ma = 250 # average current draw in mA
hours = capacity_mah / current_ma
print("Runtime:", hours, "h")
print(f"That is {hours * 60:.0f} minutes")Output:
Runtime: 8.0 h
That is 480 minutesWhat each part does
# starts a comment: Python ignores it, people read it. capacity_mah = 2000 creates a variable: a name that stores a value. / divides. print(...) shows values, separated by spaces. The f"..." is an f-string: anything in { } is worked out and put into the text, and :.0f means 'show with 0 decimal places'.
Units live in names and comments
Python does not know what a milliamp is. It only sees numbers. So engineers put units into names (current_ma) and comments. Here mAh ÷ mA leaves hours, so the variable is called hours. If the units in a calculation don't cancel to what you expect, the formula is wrong.
Common mix-ups
print(2000 / 250) prints 8.
✓ It prints 8.0, because / always produces a float in Python 3.The program knows the numbers are in mAh and mA.
✓ Python only sees numbers. Units are your job, which is why they go in names and comments.
Examples to try
Worked solutions are in the interactive chapter online.
Break a machine's job into steps: example 1
Decompose 'keep the vaccine fridge between 2 °C and 8 °C' and write the decide step precisely.
Flowcharts: drawing decisions and loops: example 1
Start 40 L, add 25 L per pass, loop while level < 120. Trace it.
Trace every case with a rule table: example 1
Brief: 'Metal parts go to bin A. Large non-metal parts go to bin B. Everything else goes to bin C.' Which bin gets a small red plastic part?
Your first Python program: battery runtime: example 1
The node sleeps at 0.5 mA most of the time. What runtime does the program give for current_ma = 0.5?
Interactive figures, in words
Figure 1.2 from “Break a machine's job into steps”
Choose 'Seedling watering'. Use Up and Down to put the six steps in order, then mark the two steps a computer could not follow exactly. Check, then compare each vague step with its precise version.
The step orderer lists six shuffled steps for automatic watering: read moisture at 07:00; if moisture is 35 % or more skip to the last step; open the valve; keep it open until 45 % or 60 s; close the valve; log the time and moisture. Two steps start vague ('Check the plants in the morning', 'Water until the soil is wet enough'); the task is to order the steps and spot those two.
Figure 1.3 from “Flowcharts: drawing decisions and loops”
Start at 20 L with the decision 'level < 90'. Predict how many times the pump runs, then press Step and fill in the trace table. Now switch to 'level != 90' and run it again. Try a start of 30 L too: why does != work there but not from 20 L?
The flowchart runner shows: Start (read level) → decision 'level < 90?' → if yes, pump one pass adding 15 L and return to the decision; if no, pump off and stop. A slider sets the starting level and a switch changes the decision to 'level != 90'. From 20 L the trace table reads 20, 35, 50, 65, 80, 95 (stop) with '<', but with '!=' the levels pass 90 and keep rising past the 120 L tank capacity.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write a program that prints a battery's run time in hours and days from its capacity and the device's current.
Open online - BUILD: Traffic system, level 1 (BUILD level)
Write the junction's rules as a rule table and check that every combination of sensor inputs has an action.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Which step is too vague for a computer?
- Read the soil-moisture sensor at 07:00
- Water until the soil is wet enough
- Close the water valve
Check it in “Break a machine's job into steps”
2. A step says 'Open the valve until moisture reaches 45 %'. What is the safest improvement?
- Remove the step
- Add 'or 60 s have passed, whichever comes first'
- Change 45 % to 100 %
Check it in “Break a machine's job into steps”
3. In a flowchart, what does a diamond mean?
- An action, such as 'pump on'
- A decision with a yes exit and a no exit
- The end of the algorithm
Check it in “Flowcharts: drawing decisions and loops”
4. Why add 'or 20 passes have run' to the tank loop?
- To make it faster
- So a failed level sensor cannot keep the pump running for ever
- It is needed for the program to start
Check it in “Flowcharts: drawing decisions and loops”
5. A sorting machine's decision depends on 4 yes/no sensors and one selector switch with 2 positions. How many different input combinations must a complete test table contain?
Answer: rows
Check it in “Trace every case with a rule table”
6. A rule table for 3 yes/no sensors has only 7 rows. What is the risk?
- None: 7 is close enough
- One combination has no defined action, so the machine's behaviour there is unknown
- The machine will run more slowly
Check it in “Trace every case with a rule table”
7. A sensor node runs from a 2500 mAh battery and draws a steady 50 mA. A program computes hours = 2500 / 50 and then minutes = hours * 60. What value does minutes hold, in minutes? (Ignore the battery ageing or the voltage dropping.)
Answer: min
Check it in “Your first Python program: battery runtime”
8. Which variable name is best for a current measured in milliamps?
- c
- current
- current_ma
Check it in “Your first Python program: battery runtime”
Engineering applications
Safety interlocks
Machine guards, lift doors and kiln controllers are specified as rule tables first. Listing every combination of sensor states exposes the one nobody thought of, such as a door sensor failing open while the motor runs.
Planning saves debugging
Ten minutes spent ordering steps and drawing the loop often saves an hour of debugging. A flowchart that never reaches its stop box is a program that never ends.
Summary
- Decompose a job into small, exact steps with clear inputs, outputs and a stopping rule.
- Flowcharts show decisions as diamonds and loops as arrows that go back.
- n on/off inputs make 2^n cases; a rule table lists them all so none is missed.
- Python runs your steps literally, top to bottom; names and units belong in the code.
Glossary
- Variables and assignment
- An assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result.
- Comparisons and Boolean expressions
- Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10.
- Truth table
- A truth table lists the output of a logic function for every possible combination of its inputs; n inputs need 2^n rows.
- Block diagram
- A block diagram shows a system as labelled boxes connected by arrows, each arrow naming what flows between them: power, a signal, data or a force.
Project: A pump controller on paper and in Python
A tank has a low-level sensor, a high-level sensor and a pump. Decompose the controller's job, draw its flowchart, write the full rule table including impossible sensor combinations, and implement it as a Python function that you call for every row of the table.
Deliverables
- A flowchart with a clear stop or repeat
- A complete rule table with an action for every row
- The function and a printout of every case
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
2. Values, types and formulas
A variable is a name stuck on a value, and the value has a type: whole number, decimal, text or list. Types decide what operations mean: 7 // 2 is 3, "7" + "2" is "72". Decimals are stored in binary, so 0.1 + 0.2 is not quite 0.3, and engineers compare floats with a tolerance. With that settled, turning a formula into code is careful work with brackets, units and the order of operations.
Figure 2.1. Floats are close, not exact (described in words)
A Python prompt shows 0.1 + 0.2 evaluating to 0.30000000000000004. The error is about 5.6e-17, so math.isclose(0.1 + 0.2, 0.3) returns True and is the right way to compare.
Explanation
2.1 How the interpreter reads your program
You compute current = voltage / resistance, then change the voltage. Does current change too?
One line at a time, top to bottom
The interpreter starts at line 1. For an assignment it works out the right-hand side using the values that exist right now, then stores the result under the name on the left. Then it moves to the next line. Nothing goes back up unless a loop or function tells it to.
Assignment is a snapshot
voltage_v = 12
resistance_ohm = 48
current_a = voltage_v / resistance_ohm
print(current_a) # 0.25
voltage_v = 24 # changing it now does not update current_a
print(current_a) # still 0.25To get the new current you must run the calculation again.
Names must exist before you use them
If line 2 uses resistance_ohm but line 3 is where it is created, Python stops at line 2 with NameError: name 'resistance_ohm' is not defined. The fix is to move the assignment above the line that needs it. A typo in a name gives the same error.
Common mix-ups
Variables update automatically when the values they were made from change, like spreadsheet cells.
✓ A variable holds the value from when its line ran. Recompute it to update it.= in Python means 'is equal to'.
✓ = means 'store'. Equality is tested with ==.
2.2 Variables that track a changing machine
A robot adds speed × time to its distance fifty times a second. How does one variable keep track of all that?
Names that explain themselves
distance_m, speed_m_per_s, parts_made say what they are and in which unit. Python names use letters, digits and underscores, cannot start with a digit and are case-sensitive (Speed and speed are different). Clear names are the cheapest documentation there is.
Updating from the old value
parts_made = parts_made + 1 reads the old value, adds 1 and stores the result: a counter. distance_m = distance_m + speed_m_per_s * dt_s is a running total. The short form parts_made += 1 does the same. Both need a starting value first, such as parts_made = 0.
Swapping without losing data
left_c, right_c = 31.5, 29.0
left_c, right_c = right_c, left_c
print(left_c, right_c) # 29.0 31.5Python evaluates the whole right side first, then assigns, so nothing is overwritten too early. The step-by-step version needs a spare: spare_c = left_c, then left_c = right_c, then right_c = spare_c.
Common mix-ups
a = b then b = a swaps two values.
✓ The first line overwrites a, so its old value is gone. Use a spare or a, b = b, a.Short names like x and t make code tidier.
✓ In engineering code, names with units (time_s, temp_c) prevent mistakes that cost far more than a few keystrokes.
2.3 int, float, str and list
A sensor file says "23.5". Add 0.4 and Python refuses. Why is a number in quotes not a number?
Five types you will use every day
int: whole numbers, 135. float: numbers with a decimal point, 23.5. str: text in quotes, "23.5". bool: True or False, the result of a comparison. list: an ordered collection, [21.5, 22.0, 22.4]. Ask type(x) to check.
Three kinds of division
seconds = 135
minutes = seconds // 60 # 2 (floor division)
leftover_s = seconds % 60 # 15 (remainder)
print(f"{minutes} min {leftover_s} s")
print(7 / 2) # 3.5 (always a float)// and % together split a quantity into whole units and what is left over: seconds into minutes, parts into boxes.
Text is not a number until you convert it
"23.5" + 0.4 raises a TypeError. float("23.5") + 0.4 gives 23.9. int("42") gives 42, but int("4.2") raises a ValueError, and int(9.99) chops to 9, it does not round. With strings, + joins text: "7" + "2" is "72".
Common mix-ups
int(9.99) rounds to 10.
✓ int() chops the fraction: int(9.99) is 9. Use round() to round./ gives an int when the answer is whole.
✓ In Python 3, / always gives a float: 6 / 3 is 2.0.
2.4 Why 0.1 + 0.2 is not 0.3
Ask Python whether 0.1 + 0.2 == 0.3 and it says False. Is your computer broken?
See it in code
import math
total = 0.1 + 0.2
print(total) # 0.30000000000000004
print(total == 0.3) # False
print(math.isclose(total, 0.3)) # True
print(abs(total - 0.3) < 1e-9) # TrueThe last two lines are how engineers compare measured or computed values: within a stated tolerance.
Errors can accumulate
One addition is off by about 10⁻¹⁷. Add 0.1 a million times and the errors can add up to something you can see. A timer that does t = t + 0.1 every tick slowly drifts. The cure is to count whole ticks in an int and compute t = ticks * 0.1 when needed.
Practical rules
Never test floats with ==; use a tolerance that means something physically (1 mV, 0.01 °C). Keep money and counts in ints (pence, millimetres, ticks). Round only for display, with round() or an f-string such as f"{x:.2f}", not in the middle of a calculation.
Derivation: Why 0.1 cannot be written exactly in binary
In base 10, 1/3 = 0.333… never ends, because 3 does not divide any power of 10. A fraction ends in base 10 only if its denominator is built from 2s and 5s (the factors of 10).
In base 2, a fraction ends only if its denominator is a power of 2. 1/2 = 0.1₂ and 1/4 = 0.01₂ are exact, so 0.5 and 0.25 are stored perfectly.
0.1 = 1/10 = 1/(2 × 5). The factor 5 is not a power of 2, so in binary 0.1 repeats for ever: 0.000110011001100…₂.
A Python float keeps 53 binary digits, so it stores the nearest value it can: 0.1000000000000000055511151231257827… That error is tiny (about 5.6 × 10⁻¹⁸) but not zero.
0.1 + 0.2 adds two rounded values and rounds again. The result lands one step above the float nearest to 0.3, so
0.1 + 0.2 == 0.3is False whilemath.isclose(0.1 + 0.2, 0.3)is True.
Common mix-ups
0.1 + 0.2 != 0.3 means Python has a bug.
✓ It is how binary floating point works in almost every language. Python is doing exactly what IEEE 754 specifies.Floats are random or unreliable.
✓ Floats are deterministic and very accurate (about 16 significant digits). Only exact equality tests and long accumulations need care.
2.5 Translate a formula into Python
Two programs compute a voltage divider's output. One says 3.4 V, the other 2211 V. Which pair of brackets is missing?
Python's order of operations
- Brackets. 2. Powers
**(worked right to left). 3. Unary minus, so-3 ** 2is-9. 4.*,/,//,%from left to right. 5.+,-from left to right. When in doubt, add brackets: they cost nothing and show your intent.
A translation recipe
- Name each quantity with its unit:
mass_kg,speed_m_per_s. 2. Replace a fraction bar with/and wrap the whole top and bottom in brackets. 3. Write powers with**. 4. Run it with numbers you can check by hand.
mass_kg = 1.2
speed_m_per_s = 3
energy_j = 0.5 * mass_kg * speed_m_per_s ** 2
print(round(energy_j, 2)) # 5.4Units check and estimate
For E = ½mv²: kg × (m/s)² = kg·m²/s² = J, so the formula is consistent. Estimate: ½ × 1 × 3² ≈ 4.5, close to 5.4. If an answer is out by a factor of 1000 or has the wrong unit, a conversion or bracket is missing.
Derivation: Average speed is total distance over total time
A robot drives d₁ = 120 m in t₁ = 40 s, then d₂ = 80 m in t₂ = 60 s.
Average speed means one steady speed that covers the same total distance in the same total time: v = (d₁ + d₂) / (t₁ + t₂).
Substitute: v = (120 + 80) / (40 + 60) = 200 m / 100 s = 2.0 m/s.
Averaging the two speeds gives (3.0 + 1.33) / 2 ≈ 2.17 m/s, which is wrong because the robot spends longer on the slow leg.
In Python the brackets carry the fraction bar:
(d1_m + d2_m) / (t1_s + t2_s). Without them,d1_m + d2_m / t1_s + t2_sgives 120 + 2 + 60 = 182.0, with meaningless units.
Common mix-ups
Python works out a line from left to right, whatever the operators.
✓ Precedence comes first: ** before * and /, which come before + and −. Left to right only applies within the same level.Extra brackets are bad style.
✓ Brackets that show intent are good style in engineering code, especially around a whole numerator or denominator.
Examples to try
Worked solutions are in the interactive chapter online.
How the interpreter reads your program: example 1
Trace: speed = 2; time = 5; distance = speed * time; speed = 3; print(distance).
Variables that track a changing machine: example 1
distance_m = 0; speed 1.5 m/s for two steps of 2 s, then 0.5 m/s for one step of 2 s. Final distance?
int, float, str and list: example 1
A process takes 7384 s. Write it as hours, minutes and seconds with // and %.
Why 0.1 + 0.2 is not 0.3: example 1
A test asserts led_resistor(3.3, 2.0, 10) == 130 and fails. The function returns 129.99999999999997. Is the function wrong?
Translate a formula into Python: example 1
Write F = C × 9/5 + 32 in Python and check it at 100 °C.
Interactive figures, in words
Figure 2.2 from “How the interpreter reads your program”
Start with 'Battery runtime' and press 'Run next line' one line at a time, watching the variable table. Then try 'Odometer update' (predict distance_m before each step) and 'Used before it exists': which line fails, and why?
The program tracer shows a short Python program, highlights the line just run and lists every variable with its value and type after that line. For example, in 'Battery runtime', after line 3 the table shows capacity_mah 2000 (int), current_ma 250 (int), hours 8.0 (float). In 'Used before it exists', line 2 stops with a NameError because resistance_ohm is created only on line 3.
Figure 2.3 from “int, float, str and list”
Predict the value and type of each expression before you click it. Start with 7 / 2, 7 // 2 and 6 / 3, then the string ones. In 'Try your own numbers', find two numbers where // and / give the same value but different types.
The type inspector lists expressions with their Python results: 7 / 2 → 3.5 (float); 6 / 3 → 2.0 (float); 7 // 2 → 3 (int); 135 // 60 → 2 and 135 % 60 → 15 (int); "7" + "2" → '72' (str); "23.5" + 0.4 → TypeError; float("23.5") + 0.4 → 23.9; int("4.2") → ValueError; int(9.99) → 9. A second panel computes any two numbers with any operator and shows the result and its type.
Figure 2.4 from “Why 0.1 + 0.2 is not 0.3”
Add 0.1 one time, two times, three times… When does == first say False? Find a number of additions where == says True again. Then look at what Python really stores for 0.1, 0.5 and 0.25: which ones are exact?
The float explorer adds 0.1 to a total n times and prints the result as Python does: n = 1 gives 0.1, n = 2 gives 0.2, n = 3 gives 0.30000000000000004 (== 0.3 is False, math.isclose is True), n = 8 gives 0.7999999999999999. A second panel shows the exact stored values: 0.1 is 0.1000000000000000055511151231257827021181583404541015625, while 0.5 and 0.25 are exact.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Add 0.1 to a total ten times and compare the result with 1.0 using == and math.isclose.
Open online - Equation Lab: Functions (Equation Lab exploration)
Type a formula with powers and division, then predict its value before evaluating to check operator precedence.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Trace this Python by hand: x = 8; x = x + 1; x = x * 4; x = x - 20; print(x). What number is printed?
Answer:
Check it in “How the interpreter reads your program”
2. Which program raises a NameError?
- x = 3 then print(x)
- print(y) then y = 3
- z = 3 then z = z + 1
Check it in “How the interpreter reads your program”
3. count = 0, then count += 1 runs 3 times, then count = count * 2 runs once. What is count?
Answer:
Check it in “Variables that track a changing machine”
4. A machine makes 26 parts and packs them in boxes of 12. What does Python give for 26 // 12 (full boxes)?
Answer: parts
Check it in “int, float, str and list”
5. reading = "23.5". Which line gives the number 23.9?
- reading + 0.4
- float(reading) + 0.4
- int(reading) + 0.4
Check it in “int, float, str and list”
6. Which test is the right way to check that a computed voltage v is 3.3 V?
- v == 3.3
- abs(v - 3.3) < 0.001
- v = 3.3
Check it in “Why 0.1 + 0.2 is not 0.3”
7. A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts?
Answer: mV
Check it in “Why 0.1 + 0.2 is not 0.3”
8. What does Python give for -3 ** 2?
- 9
- -9
- An error
Check it in “Translate a formula into Python”
Engineering applications
Timers that drift
A loop that adds 0.1 seconds to a clock thousands of times slowly drifts, because 0.1 has no exact binary form. Counting whole ticks as integers and converting at the end avoids the error building up.
Readable formulas
Naming variables with their units, such as current_a and resistance_ohm, makes a formula check itself. If the line reads volts = current_a / resistance_ohm, the mistake is visible before it runs.
Summary
- A variable names a value; assignment replaces it, and updates such as count = count + 1 build on it.
- Types matter: int, float, str and list each define their own operations.
- Floats are binary approximations; compare them with a tolerance, never with ==.
- Precedence decides the order: -x**2 is -(x**2), so use brackets to say what you mean.
Glossary
- Variables and assignment
- An assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result.
- int and float
- Python's int holds whole numbers of any size exactly; float holds real numbers approximately, in 64-bit binary floating point with about 15 to 16 significant digits.
- Floating-point rounding and comparison
- Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.
- Operator precedence
- Python evaluates ** first, then unary minus, then *, /, // and %, then + and −, then comparisons, then not, and, or. Brackets override everything.
- Floor division and modulo
- a // b divides and rounds down to the nearest whole number; a % b gives the remainder, so that a == (a // b) * b + a % b always holds.
Project: A units-safe calculator
Write a short program that reads a wheel diameter in millimetres and a speed in revolutions per minute, converts everything to SI units in one place, and prints the vehicle speed in metres per second and kilometres per hour. Include one check that uses a tolerance rather than ==.
Deliverables
- The program with units in every variable name
- Three test values worked by hand
- A note on where a float comparison could have gone wrong
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- David Goldberg (1991). "What Every Computer Scientist Should Know About Floating-Point Arithmetic". ACM Computing Surveys 23(1), 5–48. doi:10.1145/103162.103163 Link
- Python Software Foundation. The Python Tutorial: Floating-Point Arithmetic: Issues and Limitations. Python Software Foundation. Link
3. Decisions and loops
Programs earn their keep by deciding and repeating. if, elif and else pick a branch from a measurement; the order of the tests and the edge values matter more than you would think. A for loop walks through a log of readings to find the mean, the extremes and how many crossed a threshold; a while loop keeps going until a condition is met, and needs a guaranteed way out.
Figure 3.1. One pass, three answers (described in words)
Five readings shown as bars: 21, 23, 22, 30 and 24, with a dashed threshold at 25. One pass of a loop finds the mean 24, the maximum 30 at index 3, and that 1 reading is above 25.
Explanation
3.1 Decisions from measurements: if, elif, else
A battery charger must refuse to charge below 0 °C and above 45 °C. How does a program choose between three actions?
The shape of a decision
def charge_mode(temp_c):
if temp_c < 0:
return "BLOCK: too cold"
elif temp_c <= 45:
return "CHARGE"
else:
return "BLOCK: too hot"
print(charge_mode(-3)) # BLOCK: too cold
print(charge_mode(0)) # CHARGE
print(charge_mode(45.5)) # BLOCK: too hotOnly the first true branch runs
Python checks the if, then each elif in order, and runs the block under the first condition that is True, then skips the rest. else catches everything left. So the cold check comes first, and the elif temp_c <= 45 only needs to handle temperatures that are already known to be 0 or above.
Colons, indentation and comparisons
Each if, elif and else line ends with :, and the lines that belong to it are indented (4 spaces). Comparisons give a bool: <, <=, >, >=, == (equal) and != (not equal). = stores a value and cannot be used in a condition.
Common mix-ups
All the branches whose conditions are true will run.
✓ Only the first true branch runs; the rest are skipped.Indentation is just for looks.
✓ In Python, indentation decides which lines belong to which branch.
3.2 Test the edges: boundary values
Two versions of a charger rule pass every test at 20 °C. One damages the battery at exactly 45 °C. Which test would have caught it?
Where the bugs live
A rule with thresholds at 0 and 45 °C has two boundaries. For each one, test on it (0, 45), just inside (0.5, 44.5) and just outside (−0.5, 45.5), using the smallest step the sensor can report. Six tests check both edges completely.
Expected values come from the specification
Write down what each test should give before looking at the code, by reading the specification: 'charge when 0 °C ≤ T ≤ 45 °C'. If you work out the expected value by running the code, the test can only confirm the bug.
Boundary tests as asserts
def charge_mode(temp_c):
if temp_c < 0:
return "BLOCK: too cold"
elif temp_c <= 45:
return "CHARGE"
else:
return "BLOCK: too hot"
assert charge_mode(-0.5) == "BLOCK: too cold"
assert charge_mode(0) == "CHARGE"
assert charge_mode(45) == "CHARGE"
assert charge_mode(45.5) == "BLOCK: too hot"
print("boundary tests passed")Common mix-ups
If the code works for normal values, it works.
✓ Comparison mistakes only show at the boundary. Normal values cannot find them.Testing 0 and 45 is enough.
✓ Also test one sensor step either side, so you know the boundary is in exactly the right place.
3.3 for loops: summarise a sensor log
A motor logged a temperature every minute for a shift: 480 readings. How do four lines of Python find the average?
The pattern
readings_c = [41.2, 42.0, 43.5, 47.9, 52.3, 49.0, 44.1]
total = 0.0
for r in readings_c:
total = total + r
mean_c = total / len(readings_c)
print(f"mean {mean_c:.2f} °C") # mean 45.71 °CSet up before the loop, update inside it (indented), use the result after it.
What the loop really does
for r in readings_c: makes r refer to the first reading, runs the indented block, then moves r to the next reading, until the list runs out. The list is not changed. Python also has sum(readings_c) and len(readings_c), but writing the loop yourself is how you add counts, flags and checks.
Empty lists and other edge cases
If the log is empty the loop body never runs, len is 0, and total / len(readings_c) raises ZeroDivisionError. Check first: if len(readings_c) > 0: … else: print("no readings"). A single reading, and readings that are all equal, are good tests too.
Common mix-ups
The loop variable r is the position in the list.
✓ r is each reading's value. Use enumerate(readings) if you also need the position.A loop over an empty list raises an error.
✓ It simply runs zero times. The error comes later, if you divide by the count.
3.4 Count, flag and find extremes
A greenhouse thermometer's daily mean is a perfect 22.0 °C, yet it reported −40 °C and 85 °C. How could a mean hide that?
Count with an if inside a loop
readings_c = [21.4, 21.6, -40.0, 21.9, 22.1, 85.0, 22.0]
hottest = readings_c[0]
coldest = readings_c[0]
glitches = 0
for r in readings_c:
if r > hottest:
hottest = r
if r < coldest:
coldest = r
if r < -10 or r > 50:
glitches += 1
print(hottest, coldest, glitches) # 85.0 -40.0 2Why start from the first reading?
Starting hottest = 0 fails when every reading is below 0 °C, as in a freezer log: the 'hottest' would wrongly stay 0. Starting from readings_c[0] (or None, then filling it on the first pass) always gives a real reading. Python's max() and min() do the same and should agree with your loop.
Plausibility checks catch glitches
A greenhouse is never −40 °C. A plausibility band (here −10 to 50 °C) flags readings that are physically impossible, usually from a loose wire, electrical noise or a sensor fault. Flag and count them, report them, and leave them out of the mean, rather than silently averaging them in.
Common mix-ups
If the mean is normal, the data is fine.
✓ A mean can hide extreme or impossible readings. Check the max, min and plausibility too.Glitchy readings should be quietly deleted.
✓ Flag, count and report them. A rising glitch count is itself a warning that a sensor is failing.
3.5 while loops: repeat until it's done
A motor cools by 20 % of its excess heat each minute. How long until it is safe to touch, without knowing the answer in advance?
The cooling simulation
excess_c = 60.0 # motor is 60 °C above the room
minutes = 0
while excess_c > 5:
excess_c = excess_c * 0.8
minutes += 1
print(minutes, round(excess_c, 2)) # 12 4.12The condition is checked before every pass. If it is false at the start, the body never runs.
Every while loop needs progress
Something inside the loop must move it towards stopping: here excess_c shrinks. If nothing changes, the loop runs for ever. For machines, add a guard as well: while excess_c > 5 and minutes < 120: stops even if the model or a sensor misbehaves.
for or while?
Use for when you know what to go through: every reading in a list, each of 10 test cases. Use while when you stop on a condition: until the tank is full, until the error is small, until the user types 'q'. A for loop over a list always ends; a while loop ends only if you make it.
Common mix-ups
A while loop always runs at least once.
✓ It checks first. If the condition is false at the start, the body never runs.Infinite loops only happen when you write while True.
✓ Any condition that can never become false, like != on a value that skips past the target, loops for ever.
Examples to try
Worked solutions are in the interactive chapter online.
Decisions from measurements: if, elif, else: example 1
Write a fan rule: 100 % at 50 °C or more, 50 % from 35 °C up to 50 °C, otherwise off. What is the fan at 35 °C and at 49.5 °C?
Test the edges: boundary values: example 1
A conveyor stops if the load is over 25.0 kg. The scale reads in 0.1 kg steps. Choose boundary tests and their expected results.
for loops: summarise a sensor log: example 1
Readings 3.71, 3.69, 3.66, 3.62 V from a battery. Find the mean with a loop.
Count, flag and find extremes: example 1
Freezer log: −19.5, −18.0, −21.2, −18.9 °C. A program starts hottest = 0. What does it report, and how do you fix it?
while loops: repeat until it's done: example 1
A tank holds 1000 L and drains 15 % of what is left each minute. With a while loop, how many minutes until it is below 500 L?
Interactive figures, in words
Figure 3.2 from “Decisions from measurements: if, elif, else”
Choose Version B. Move the temperature slider and watch which return line lights up. Find the exact temperatures where the answer changes. Then switch to Versions A and C: do they ever disagree with the specification?
The boundary tester shows the charge_mode function in three versions and a temperature slider from −10 to 60 °C in 0.5 °C steps. It highlights the line that returns and compares the result with the specification (charge only from 0 °C to 45 °C inclusive). Version B matches everywhere; Version A wrongly blocks at exactly 0 °C; Version C wrongly blocks at exactly 45 °C.
Figure 3.3 from “for loops: summarise a sensor log”
Choose 'Motor temperature log'. Predict the mean and how many readings go over 50 °C, then run the loop one pass at a time and watch count, total, hottest and over change. Then try 'Empty log': why doesn't the program crash?
The loop visualiser shows the readings 41.2, 42.0, 43.5, 47.9, 52.3, 49.0, 44.1 °C as bars with a 50 °C limit line. Each step runs one loop pass and updates count, total, hottest, coldest and over. After 7 passes it prints mean 45.714285714285715, max 52.3, min 41.2, over 1. For the empty log the loop never runs and the program prints 'no readings'.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Summarise a list of temperature readings in one loop: mean, maximum, minimum and the count above a limit.
Open online - BUILD: Smart greenhouse, level 2 (BUILD level)
Read the greenhouse data and flag every hour the temperature left its safe band.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A rule is written: if temp_c >= 35: fan = 50, elif temp_c >= 50: fan = 100. What is wrong?
- Nothing
- The fan can never reach 100 %: any temperature ≥ 50 already matches the first test
- It raises a SyntaxError
Check it in “Decisions from measurements: if, elif, else”
2. Which condition tests whether a reading equals the limit?
- if reading = limit:
- if reading == limit:
- if reading := limit:
Check it in “Decisions from measurements: if, elif, else”
3. A rule should pass readings from 10 to 60 inclusive, in steps of 1. Which set of tests is best?
- 20, 30, 40
- 9, 10, 11, 59, 60, 61
- 0, 100
Check it in “Test the edges: boundary values”
4. A rule has three thresholds. Using on, just-below and just-above tests for each, how many boundary tests is that?
Answer: tests
Check it in “Test the edges: boundary values”
5. A loop totals and counts these temperature readings (°C): [18.0, 25.4, 31.8, 31.6, 21.9, 26.6]. What is total / count, in °C?
Answer: °C
Check it in “for loops: summarise a sensor log”
6. What happens with total / len(readings) when readings is []?
- It gives 0
- ZeroDivisionError
- It gives None
Check it in “for loops: summarise a sensor log”
7. To find the hottest reading in a loop, what should hottest start as?
- 0
- The first reading in the list
- 100
Check it in “Count, flag and find extremes”
8. Which while loop never ends?
- n = 0; while n < 5: n += 1
- n = 10; while n > 0: n -= 2
- n = 1; while n != 10: n += 2
Check it in “while loops: repeat until it's done”
Engineering applications
Alarm thresholds
A temperature alarm that fires above 30 °C must be tested at 29.9, 30 and 30.1, because whether the boundary uses > or >= is a real design decision. Most threshold bugs live exactly on the line.
Log summaries
Test rigs produce thousands of readings. A single loop that keeps a running total, a running maximum and a count turns the raw log into the few numbers a report needs.
Summary
- if/elif/else tests in order and runs the first branch that is true, so order the tests carefully.
- Boundary testing checks just below, on, and just above every threshold.
- A for loop can build a total, a count and an extreme in one pass; initialise each one correctly.
- A while loop needs a condition that will eventually become false, or a safety limit.
Glossary
- if, elif and else
- if runs a block only when its condition is true; elif tests another condition if earlier ones were false; else catches everything left.
- for loops and range
- A for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop.
- while loops
- A while loop repeats its body as long as its condition stays true, checking the condition before each pass.
- Comparisons and Boolean expressions
- Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10.
- Mean and median
- The mean is the sum of the values divided by how many there are; the median is the middle value once the values are sorted.
Project: The sensor-log checker
Write a program that reads a list of readings, reports their mean, minimum, maximum and the index of the maximum, counts readings outside a safe band, and handles an empty list without crashing. Test it at every boundary of the band.
Deliverables
- The program
- A table of boundary tests with expected and actual results
- One bug you found by testing, and its fix
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- Python Software Foundation. The Python Tutorial. Python Software Foundation. Link
4. Functions, tests and debugging
A function packages a calculation behind a name: inputs in, one value returned. Once it exists, you can test it with assert against answers worked out independently, and reuse it with confidence. When something breaks, read the traceback from the bottom, reproduce the bug, form a hypothesis and test it. Finally, check inputs at the door, so bad data fails loudly instead of quietly producing nonsense.
Figure 4.1. Inputs in, one value returned (described in words)
A function machine labelled wheel_distance takes counts = 1200, cpr = 600 and diameter = 0.065 and returns π × 0.065 × 1200 / 600 = 0.408 m. Return, don't print: the caller decides.
Explanation
4.1 Package a calculation as a function
A robot converts wheel rpm to speed in six places in its code. One of them has a bug. How do you fix all six at once?
Define once, call many times
import math
def wheel_speed_m_per_s(rpm, diameter_m):
"""Ground speed of a wheel in m/s, from its rpm and diameter in metres."""
return rpm / 60 * math.pi * diameter_m
print(round(wheel_speed_m_per_s(120, 0.065), 3)) # 0.408def names the function, the brackets list its parameters, and return hands back the result.
Return, don't just print
A returned value can be stored, compared, tested or passed to another function: if wheel_speed_m_per_s(rpm, d) > 1.5: slow_down(). Printing inside a function only shows text and gives back None. Keep functions quiet; print at the top level of the program.
A docstring is a promise
The triple-quoted line under def is a docstring. It says what the function does and the units of its inputs and output. Anyone using the function should be able to trust it without reading the body, and tests (next lesson) check that the promise is kept.
Common mix-ups
A function that prints its answer has returned it.
✓ Printing shows text; only return gives the caller a value.Parameters must have the same names as the variables you pass in.
✓ Arguments are matched by position (or by name=value). The names inside and outside can differ.
4.2 Promises and proof: tests with assert
Three versions of a °C-to-°F function all run without errors. Only one is right. How can three lines of tests tell them apart instantly?
A test is an assert
def c_to_f(c):
"""Convert a temperature in °C to °F."""
return c * 9 / 5 + 32
assert c_to_f(0) == 32
assert c_to_f(100) == 212
assert c_to_f(-40) == -40
print("all tests passed")assert condition does nothing if the condition is True and stops with AssertionError if it is False.
Expected values must be independent
Work out each expected value from somewhere other than the code: a reference point (water freezes at 0 °C = 32 °F), a hand calculation or a datasheet. If you copy the function's own output into the test, the test will happily confirm a bug.
Floats need a tolerance
(3.3 - 2.0) / 0.01 is 129.99999999999997, so == 130 fails even though the function is right. Write assert abs(led_resistor_ohm(3.3, 2.0, 10) - 130) < 1e-9, or math.isclose(...). Pick a tolerance that makes physical sense for the quantity.
Common mix-ups
If code runs without an error, it is correct.
✓ Running proves only that it does not crash. Tests against known answers show whether it is right.A failing test always means the function is wrong.
✓ Sometimes the test is wrong, for example by comparing floats with ==. Check both.
4.3 Read the traceback
Your program crashes with six lines of red text. Most people read the top. Why does the answer start at the bottom?
Bottom up
Traceback (most recent call last):
File "log.py", line 7, in <module>
print(mean([]))
File "log.py", line 5, in mean
return total / len(readings)
ZeroDivisionError: division by zeroLast line: the error type and message. Just above: the file, line and code where it happened. Higher up: the chain of calls that got there (line 7 called mean).
Three kinds of error
Syntax errors stop the program before anything runs: if x = 5: (Python even suggests ==). Runtime errors crash it part-way: dividing by zero, adding text to a number. Logic errors never crash: the program runs and gives a wrong answer. Logic errors are the hardest, so tests matter.
The usual suspects
NameError: a misspelt name or one used before it is assigned. TypeError: the wrong type, such as "23.5" + 0.4. ValueError: right type, bad value, such as float("ERR"). ZeroDivisionError: dividing by zero, often an empty list. IndexError: a list position that does not exist, such as readings[7] in a 7-item list.
Common mix-ups
The first line of a traceback is the most important.
✓ The last line names the error, and the line above it shows where. Read from the bottom.No error message means no bug.
✓ Logic errors give wrong answers silently. Only tests and checks reveal them.
4.4 Reproduce, hypothesise, test: hunting logic bugs
A robot's speed log says 240 m/s. Nothing crashed. Where do you even start?
The method
- Reproduce: find a small input that always shows the bug. 2. Hypothesise: 'I think the first reading is never added.' 3. Test the hypothesis: add a print, or try an even smaller input. 4. Fix the cause, not the symptom. 5. Keep a test that would have caught it.
Print probes
A print just after a suspect line shows the values at that moment: print("i", i, "total", total) inside a loop. If i starts at 1, the hypothesis is confirmed. Remove or comment out probes once the bug is fixed; keep the assert you add.
Three classic logic bugs
Off-by-one: range(1, n) skips index 0; range(n + 1) runs one too far. Indentation: a return inside a for loop returns after the first item. Units: millimetres divided by seconds labelled m/s is 1000 times too big. The first two show in a probe of the loop; the third shows in a units check.
Common mix-ups
Debugging means changing things until it works.
✓ Debugging means forming and testing hypotheses until you know the cause, then fixing that cause.Once it's fixed, the bug is gone for good.
✓ Bugs come back when code changes. A test that would have caught it keeps it gone.
4.5 Catch bad data before it bites
A data logger writes ERR whenever its sensor hiccups. Should your program crash, skip the line, or quietly count it as zero?
Validate every line
def parse_reading(line):
"""Return the reading in °C, or None if the line is not a plausible reading."""
try:
value = float(line)
except ValueError:
return None
if value < -40 or value > 125:
return None
return value
lines = ["21.5", "ERR", "", "-999.0", "22.1"]
good = []
for line in lines:
value = parse_reading(line)
if value is not None:
good.append(value)
print(good) # [21.5, 22.1]Two different checks
The conversion check (try / except ValueError) catches lines that are not numbers at all: ERR, blanks, '--'. The plausibility check catches numbers that cannot be real: −999.0, 130.5. The band comes from the sensor's datasheet (here −40 to 125 °C, typical of small temperature sensors) or from physics.
Never hide the evidence
Count what you reject and report it: '3 of 480 lines rejected'. Never replace bad lines with 0, which drags the mean down and looks like a real reading. Catch only the error you expect (except ValueError), not every error, so genuine bugs still show up.
Common mix-ups
If float() succeeds, the reading is good.
✓ −999.0 and 130.5 convert fine but are impossible. Range checks are also needed.Catching every exception makes a program robust.
✓ It makes bugs invisible. Catch the specific errors you expect and handle them deliberately.
Examples to try
Worked solutions are in the interactive chapter online.
Package a calculation as a function: example 1
Write mean(values) that returns the mean of a non-empty list, and use it for [41.2, 42.0, 43.5].
Promises and proof: tests with assert: example 1
Write tests for current_ma(v, r_ohm), which returns the current in mA.
Read the traceback: example 1
A traceback ends: IndexError: list index out of range, at line 4: last = readings[len(readings)]. Explain and fix.
Reproduce, hypothesise, test: hunting logic bugs: example 1
count_over([48, 52, 55, 49, 61], 50) returns 0 instead of 3. Find the bug.
Catch bad data before it bites: example 1
What does parse_reading do with "nan"?
Interactive figures, in words
Figure 4.2 from “Package a calculation as a function”
Choose wheel_speed_m_per_s. Feed it 60 rpm and 0.1 m and work out the answer by hand first. Then compare versions A, B and C: which one matches your hand calculation? Run the tests to confirm.
The function machine shows a Python function with a docstring, three versions of its body and a set of assert tests. For wheel_speed_m_per_s: version A (rpm / 60 * math.pi * diameter_m) passes all three tests; version B forgets to divide by 60 (60 rpm, 0.1 m gives 18.85 instead of 0.314 m/s); version C uses 2π with the diameter (0.628 m/s).
Figure 4.3 from “Read the traceback”
Work through 'Text plus a number', 'Mean of an empty log' and 'One equals sign'. For each, read the traceback from the bottom, pick the line you suspect and check. Use the print probe to see the variables just before the crash.
The bug hunt shows a short program, what was expected and what actually happened. 'Text plus a number' crashes on line 3 with TypeError: can only concatenate str (not "float") to str. 'Mean of an empty log' crashes on line 5 inside mean, called from line 7, with ZeroDivisionError. 'One equals sign' fails before running with a SyntaxError on line 3, suggesting '=='. Selecting a line and checking explains the cause and the fix.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write wheel_distance with a docstring and three assert tests, one of which uses a tolerance.
Open online - BUILD: Sorting machine, level 2 (BUILD level)
Write the sorting rules as a function and test it on every kind of part, including a missing reading.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. def wheel_speed_m_per_s(rpm, diameter_m): return rpm / 60 * math.pi * diameter_m. What does wheel_speed_m_per_s(150, 0.05) return, in m/s?
Answer: m/s
Check it in “Package a calculation as a function”
2. Why is return better than print inside a calculation function?
- return is faster to type
- The returned value can be used in further calculations and tests
- print does not work inside functions
Check it in “Package a calculation as a function”
3. You are testing def current_ma(v, r_ohm): return v / r_ohm * 1000. To write assert abs(current_ma(9, 100) - EXPECTED) < 0.01, work EXPECTED out by hand with Ohm's law. What is it, in mA?
Answer: mA
Check it in “Promises and proof: tests with assert”
4. A correct function returns 129.99999999999997 for an expected 130. Which test is right?
- assert result == 130
- assert abs(result - 130) < 1e-9
- assert int(result) == 130
Check it in “Promises and proof: tests with assert”
5. Which part of a traceback tells you the kind of error?
- The first line, 'Traceback (most recent call last)'
- The last line
- The middle line
Check it in “Read the traceback”
6. A program gives a wrong total. What is the best first step?
- Rewrite the whole program
- Find a small input that always shows the wrong total
- Change the < signs to <= and see
Check it in “Reproduce, hypothesise, test: hunting logic bugs”
7. distance_mm differences divided by interval_s are printed as m/s and look 1000 times too big. Best fix?
- Divide the result by 1000 to convert mm/s to m/s
- Multiply by 1000
- Remove the label
Check it in “Reproduce, hypothesise, test: hunting logic bugs”
8. Why write except ValueError rather than a bare except?
- It runs faster
- A bare except would also hide real bugs, such as a misspelt name
- Bare except is not allowed
Check it in “Catch bad data before it bites”
Engineering applications
Tested building blocks
Flight software and medical devices are built from small functions, each with tests that pin down its behaviour. When a function changes, its tests run again automatically, so a regression is caught before it ships.
Fail loudly
A sensor that returns −999 on error can silently drag an average down. Checking inputs and raising a clear error stops bad data from spreading through every calculation that follows.
Summary
- A function takes inputs and returns a value; return rather than print so callers can use it.
- Test against answers you worked out independently, with a tolerance for floats.
- Read tracebacks from the bottom: the last line names the error, the lines above show where.
- Debug by reproducing, hypothesising and testing one idea at a time; validate inputs at the boundary.
Glossary
- Functions and return values
- def name(parameters): defines a reusable block of code. Calling it runs the body with the given arguments, and return sends a value back to the caller.
- Exceptions: try and except
- When something goes wrong, Python raises an exception. A try block runs risky code and an except block handles a named kind of exception instead of crashing.
- Floating-point rounding and comparison
- Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.
Project: A tested utility module
Write three functions you would reuse in engineering work, such as wheel distance from encoder counts, ADC counts to volts and a safe mean that rejects empty or invalid data. Give each a docstring, input checks and at least three tests, including one edge case.
Deliverables
- The three functions with docstrings
- At least nine tests that pass
- A short log of one bug you found and how you located it
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
5. Modules, objects and data structures
Past a hundred lines, one script becomes a tangle. Modules split a program into files with clear jobs; classes bundle data with the methods that guard it, so a sensor object can keep its own readings and refuse impossible ones. Then pick the right container: a list keeps order, a set answers membership, a dictionary looks up by key, a stack undoes, and a queue serves in arrival order.
Figure 5.1. Same items in, different order out (described in words)
Items A, B and C are pushed in that order. A stack gives them back as C, B, A (last in, first out); a queue gives them back as A, B, C (first in, first out).
Explanation
5.1 One script is not a system
A rover planner works perfectly as one 600-line file. Then you change a unit conversion and three unrelated features break. Why?
A module is just a .py file
Any file units.py is a module called units. Another file in the same folder can write import units and call units.cm_to_m(250), or from units import cm_to_m to use the name directly. Python searches the folder of the script you ran first, then the standard library and installed packages.
Interfaces, not internals
Each module should expose a few functions or classes (its interface) and keep its helpers private. By convention, a name starting with an underscore, such as _clamp, is internal. Other modules use only the interface, so you can rewrite the inside freely as long as the interface and its tests still hold.
Arrows only go one way
Draw an arrow from each module to the modules it imports. Good packages form layers: small utility modules at the bottom, the program's entry point at the top, and no loops. A circular import (A imports B and B imports A) means neither can be loaded or tested on its own; fix it by moving the shared code down a layer or the calling code up.
Common mix-ups
Splitting code into files makes it slower.
✓ Imports happen once and are cached; the cost is negligible. The benefit is code you can understand, test and change in pieces.If it runs, the structure doesn't matter.
✓ Structure decides how much breaks when you change something. One-way dependencies keep that blast radius small.
5.2 One blueprint, many sensors
A robot has six identical range sensors, each with its own offset and its own readings. Do you write six sets of variables, or one blueprint?
Class, instance, self
class RangeSensor: defines a new type. front = RangeSensor("front", 2) calls __init__ to build one instance. Inside each method, self is the particular object the method was called on, so self.readings means this sensor's readings.
Attributes live on the object
Assigning self.offset_cm = offset_cm stores a value on that one object; vars(front) shows them. Python looks up an attribute on the object first, then on its class. Constants that every instance shares, like unit = "cm", can sit on the class.
The shared-list trap
A list (or dict) written in the class body exists once, for every instance. Appending through self.readings changes that one shared list, so every sensor sees every reading. Create mutable state inside __init__ so each object gets its own.
Common mix-ups
self is a keyword that means the class.
✓ self is just the conventional name for the first parameter, which receives the instance the method was called on.Each object gets its own copy of every class attribute.
✓ Class attributes are shared. Only attributes assigned on self belong to one object.
5.3 List, tuple, set or dict? Pick the right container
Checking whether a part number is in a list of 100,000 parts takes up to 100,000 comparisons. With a set it takes about one. What changed?
Four containers, four questions
list: ordered, indexable, may repeat; 'what is the 5th reading?'. tuple: like a list but fixed, perfect for a record such as (row, col). set: unordered, no repeats; 'is this in the collection?'. dict: keys mapped to values; 'what is the stock of this part?'.
Why sets and dicts are fast
A set or dict computes a hash of the key, which says roughly where to look, so x in s and d[k] take about the same time whether there are 10 items or 10 million (on average). x in some_list compares items one by one: up to n comparisons.
Keys must not change
Only immutable values can be set members or dict keys: numbers, strings and tuples of them. That is another reason to store a cell as the tuple (3, 7) rather than the list [3, 7]. Lists can't be hashed, so {[3, 7]} raises TypeError.
Common mix-ups
Sets are just lists without duplicates.
✓ Sets are hash tables: unordered, with fast membership tests. That speed is the main reason to use one.Dicts are slow because they are complicated.
✓ Average dict lookup is about as fast as list indexing and far faster than searching a list.
5.4 Stacks and queues: who goes next?
A robot cell gets jobs faster than it can do them. Do you serve the newest job first, or the oldest? The answer changes everything.
Stack: last in, first out
A Python list is a stack: s.append(x) pushes onto the top, s.pop() removes and returns the top. Both are fast (O(1)). Use it for undo, for backtracking, and for depth-first search.
Queue: first in, first out
from collections import deque gives a double-ended queue. q.append(x) joins the back; q.popleft() serves the front, both in O(1). Don't use list.pop(0) for a queue: it shifts every remaining item, which is O(n).
Empty means stop
Popping from an empty list or deque raises IndexError. Loops usually run while q: (an empty container is falsy), so they end naturally when the work is done.
Common mix-ups
A list works fine as a queue.
✓ It works, but list.pop(0) is O(n). deque gives O(1) at both ends.Stacks and queues are different kinds of storage.
✓ They are the same items with different rules about which one leaves next.
Examples to try
Worked solutions are in the interactive chapter online.
One script is not a system: example 1
Split this conversion out of a planner script into its own module, then use it.
One blueprint, many sensors: example 1
Model a range sensor with a calibration offset, record readings and report their mean.
List, tuple, set or dict? Pick the right container: example 1
Store visited cells and per-cell costs for a planner.
Stacks and queues: who goes next?: example 1
Process jobs in arrival order and keep an undo history.
Interactive figures, in words
Figure 5.2 from “One script is not a system”
Select units.py, then grid.py, then main.py and count the orange modules each time. Which module is safest to change, and which is riskiest? Now tick the shortcut that lets grid.py import planner.py and read the warning.
The dependency explorer shows seven modules in layers: units.py at the bottom; grid.py and report.py import units; io_csv.py and planner.py import grid; main.py imports io_csv, planner and report; test_planner.py imports planner and grid. Changing units.py affects all five modules above it. Ticking the shortcut makes grid.py also import planner.py, creating a circular import.
Figure 5.3 from “One blueprint, many sensors”
Record a few readings on front and rear, then compare vars(front) and vars(rear). Call rear.mean() before it has readings and read the error. Now tick the bug toggle and record on front only: what happened to rear?
The inspector shows a RangeSensor class with a front sensor (offset 2 cm) and a rear sensor (offset −1 cm). Recording 50 cm on the front stores 52 in front's own list only. With the bug toggle on, readings live on the class, so the same 52 appears in both sensors' readings.
Figure 5.4 from “List, tuple, set or dict? Pick the right container”
Open Dict (inventory) mode and look up each part. Note how many names a list scan would have to compare. Look up the part that isn't stocked: what happens with [] and with .get()? Then switch to List mode and compare.
The dict mode shows an inventory of six parts. Looking up 'servo SG90' returns 6 directly; as a list of pairs a scan would compare 4 names. Looking up an unstocked 'M4 bolt' raises KeyError with square brackets but returns 0 with .get(key, 0); a list scan would check all 6 names.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Write a Sensor class that stores readings and returns their mean, and test that two sensors do not share data.
Open online - Nexus: Smart Transportation Junction (Nexus project)
Model the cars waiting at a light as a queue and count how many clear in one green phase.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. units.py defines cm_to_m. Which line lets another file call cm_to_m(250) with no prefix?
- import units
- from units import cm_to_m
- import cm_to_m from units
- include units
Check it in “One script is not a system”
2. grid.py imports planner.py so GridMap can call bfs, and planner.py imports grid.py. What is the best fix?
- Swap the order of the import lines
- Let main.py call bfs(grid, start, goal), so grid.py no longer imports planner
- Copy bfs into grid.py as well
- Put both files' code into one big file
Check it in “One script is not a system”
3. Inside record(self, raw_cm), what is self when you call rear.record(80)?
- The RangeSensor class
- The rear object
- The number 80
- A copy of front
Check it in “One blueprint, many sensors”
4. Which class definition gives each sensor its own readings list?
- readings = [] in the class body
- self.readings = [] inside __init__
- global readings
- readings = [] inside record
Check it in “One blueprint, many sensors”
5. You need the stock quantity for any part number, looked up thousands of times. Which container?
- A list of quantities
- A dict {part_no: qty}
- A set of part numbers
- A tuple of tuples, scanned each time
Check it in “List, tuple, set or dict? Pick the right container”
6. stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?
- KeyError
- 0
- None
- 120
Check it in “List, tuple, set or dict? Pick the right container”
7. A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?
Answer:
Check it in “Stacks and queues: who goes next?”
8. An editor's undo button should reverse the most recent change first. Which structure?
- A queue
- A stack
- A set
- A dict
Check it in “Stacks and queues: who goes next?”
Engineering applications
Undo
Every editor's undo button is a stack: each action is pushed, and undo pops the most recent. Print queues, message buffers and robot task lists are queues, served strictly in the order they arrived.
Fleets of sensors
A greenhouse with twenty sensors becomes twenty objects of one class, each with its own calibration and readings. A dictionary keyed by sensor name finds any one of them instantly.
Summary
- Modules split a program by job; import what you need and keep top-level code minimal.
- A class is a blueprint; each instance keeps its own data, reached through self.
- Choose containers by the question you ask most: order, membership or lookup by key.
- A stack is last in, first out; a queue is first in, first out.
Glossary
- Classes and objects
- A class is a blueprint that bundles data (attributes) and behaviour (methods). Each object made from it has its own copy of the data; self refers to that object inside a method.
- Dictionaries
- A dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time.
- Lists and indexing
- A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end.
- Slicing
- A slice seq[start:stop:step] takes items from start up to but not including stop, moving step at a time; any part can be left out.
- List comprehensions
- A list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition].
Project: A stores inventory
Model a workshop's parts store as a small package: a Part class, a dictionary from part number to Part, and a queue of incoming orders. Process the orders, report shortfalls, and keep an undo stack so the last change can be reversed.
Deliverables
- Two modules with a clear split of jobs
- Tests for ordering, shortfall and undo
- A paragraph explaining each container choice
References
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
- Thomas H. Cormen et al. (2009). Introduction to Algorithms, 3rd edition. MIT Press.
- Python Software Foundation. The Python Tutorial. Python Software Foundation. Link
6. Search, sort and cost
Two correct programs can differ by a factor of a million in speed. Linear search checks every item; binary search on sorted data halves the range each step, so a million items need about twenty comparisons. Counting operations before timing them reveals how work grows with input size, and Big-O names that growth. Breadth-first search uses a queue to explore a grid map one ring at a time.
Figure 6.1. Halving beats walking (described in words)
Worst-case comparisons compared as bars: for 1,000 items linear search needs 1000 and binary search 10; for 1,000,000 items linear search needs 1000000 and binary search 20.
Explanation
6.1 Halve it again: binary search
A sorted catalogue lists a million part numbers. How many guesses do you need to find any one, or prove it isn't there?
Linear search
Check items from the start until you find the target or run out. It works on any list, sorted or not. Worst case: n comparisons (the target is last or absent). On average, for a present target, about n/2.
Binary search
Keep a range lo..hi. Compare the target with the middle item: equal, done; smaller, search the left half; bigger, the right half. Stop when the range is empty. It needs sorted data and fast access to any index (a list, not a file you must read line by line).
The cost of sorted
Binary search is only correct if the list really is sorted: on unsorted data it can confidently report 'not found' for an item that is there. If data arrives unsorted, you pay to sort it once (next lessons). Python's bisect module implements binary search for you.
Derivation: Why the worst case is ⌈log₂(n + 1)⌉ comparisons
Each probe compares the target with the middle item of the current range. Either it matches, or the range shrinks to the left part or the right part, each holding at most half of what's left (excluding the middle item).
Let N(k) be the largest list that binary search can always settle in k probes. With one probe you can settle a list of 1: N(1) = 1.
With k probes, you spend one on the middle and must settle either side with k − 1 probes. So each side may hold N(k − 1) items: N(k) = 2·N(k − 1) + 1.
Solving: N(1) = 1, N(2) = 3, N(3) = 7, N(4) = 15, and in general N(k) = 2^k − 1.
So k probes suffice exactly when n ≤ 2^k − 1, that is 2^k ≥ n + 1. The smallest such k is ⌈log₂(n + 1)⌉.
Example: n = 1,000 needs ⌈log₂ 1001⌉ = 10 probes (2¹⁰ − 1 = 1023 ≥ 1000). Doubling n adds just one probe.
Common mix-ups
Binary search is always better than linear search.
✓ Only on sorted data with random access. For a single search of unsorted data, sorting first costs more than one linear scan.Doubling the data doubles binary search time.
✓ It adds just one comparison.
6.2 Count the steps before you time them
Checking every pair of 1,000 waypoints for collisions: is that 1,000 checks, 500,000, or a million?
Single and nested loops
A loop over range(n) runs n times. A loop inside a loop multiplies: range(a) around range(b) runs a × b times. Three nested loops over n run n³ times. Loops one after another add: n + n = 2n.
When the inner loop depends on the outer
If the inner range uses i, add up the inner counts. range(i) gives 0 + 1 + … + (n − 1) = n(n − 1)/2; range(i, n) gives n + (n − 1) + … + 1 = n(n + 1)/2. A step, range(0, n, k), runs ⌈n/k⌉ times.
Count the expensive line
You don't need to count every statement. Pick the line that runs most often (a comparison, a distance calculation) and count that. Its formula dominates the program's cost as n grows.
Derivation: Why the triangular loop costs n(n − 1)/2
The loop for i in range(n): for j in range(i): runs the inner body i times on pass i, for i = 0, 1, …, n − 1.
Total S = 0 + 1 + 2 + … + (n − 1).
Write the sum forwards and backwards and add: each column gives (n − 1), and there are n columns, so 2S = n(n − 1).
Therefore S = n(n − 1)/2. For n = 1000: 1000 × 999 / 2 = 499,500.
For large n this is about n²/2: still quadratic. Doubling n multiplies it by about 4.
Common mix-ups
Two nested loops always cost n².
✓ Only if both run n times. A dependent inner loop can give n(n − 1)/2, and a fixed inner loop of 4 neighbours gives 4n.Counting operations is pointless when computers are fast.
✓ Fast computers make large n affordable, which is exactly when quadratic counts explode.
6.3 Big-O: the shape of growth
Algorithm A takes 3n² + 50n + 1000 steps; algorithm B takes 400n. Which would you choose for a map with a million cells?
Keep the top term, drop the constant
From an exact count, keep the term that grows fastest and drop its coefficient: 5n + 20 → O(n); n(n − 1)/2 → O(n²); 4 log₂ n + 7 → O(log n). Big-O describes the shape of growth, not the exact number of steps.
The usual ladder
O(1) constant (dict lookup) < O(log n) (binary search) < O(n) (one scan) < O(n log n) (good sorts) < O(n²) (all pairs, insertion sort) < O(n³) (three nested loops). Doubling n adds a step, doubles, slightly more than doubles, quadruples, and multiplies by 8.
Predicting from a measurement
If you measure 20 ms at n = 1,000 and the code is O(n²), expect about 20 × 4 = 80 ms at n = 2,000 and 20 × 100 = 2 s at n = 10,000. Then test the prediction: if the measurement disagrees, your model of the code is wrong somewhere.
Derivation: Why constants and smaller terms are dropped
Take T(n) = 3n² + 50n + 1000. Divide by n²: T(n)/n² = 3 + 50/n + 1000/n².
As n grows, 50/n and 1000/n² shrink towards 0, so T(n)/n² approaches 3. The n² term ends up doing almost all the work.
Big-O asks only how T grows, up to a constant factor: T(n) ≤ c·n² for some constant c once n is large enough (here c = 4 works for n ≥ 66). So T(n) is O(n²).
The constant 3 is dropped because it depends on the machine and the language; the exponent 2 doesn't. Doubling n multiplies any O(n²) cost by about 4, whatever the constant.
Common mix-ups
O(n) means exactly n steps.
✓ It means the steps grow in proportion to n: 3n + 100 is O(n).Lower big-O always means faster code.
✓ Only for large enough inputs. For small inputs, constants and overheads can dominate.
6.4 Breadth-first search: a queue explores a map
Put a robot in a maze and flood it outwards one step at a time. Why does the first time the flood touches the goal give the shortest route?
The frontier is a queue
Start with the start cell in a queue. Repeatedly take the oldest cell, and add each unvisited free neighbour to the back. Because cells come out in the order they went in, every cell 1 move away is processed before any cell 2 moves away, and so on.
Visited set and came-from dict
Mark a cell visited when you add it to the queue, so it is never queued twice. Record came_from[neighbour] = current. When you reach the goal, follow came_from back to the start and reverse: that's the path.
Guarantees and limits
BFS always finds a path with the fewest moves if one exists, and reports failure after visiting every reachable cell if not. It ignores terrain cost: a short path through mud beats a long path on tarmac. Fixing that is Dijkstra's job in the term project.
Common mix-ups
BFS finds the cheapest route.
✓ It finds the route with the fewest moves. With terrain costs you need a cost-aware planner such as Dijkstra.Search algorithms 'see' the whole map at once.
✓ They only ever look at the neighbours of the cell they are expanding; the map knowledge comes from the order they expand cells.
Examples to try
Worked solutions are in the interactive chapter online.
Halve it again: binary search: example 1
Binary search that counts its comparisons, checked against linear search.
Count the steps before you time them: example 1
Count the pair checks for n waypoints and confirm with the formula.
Big-O: the shape of growth: example 1
Predict from a measurement for three growth rates.
Breadth-first search: a queue explores a map: example 1
BFS on a text map, returning the path as a list of cells.
Interactive figures, in words
Figure 6.2 from “Halve it again: binary search”
With 31 parts, pick a target and step both searches one comparison at a time. Try a part near the end and one that isn't stocked. Then switch to 127 parts: how much worse does linear search get? And binary?
The visualiser shows a sorted list of part numbers as a strip of cells. Linear search colours cells one by one from the left. Binary search probes the middle, then the middle of the remaining half, shading the range still in play. With 31 parts binary search never needs more than 5 comparisons; linear search may need 31.
Figure 6.3 from “Count the steps before you time them”
Turn on only n and n² and slide n from 2 to 1,000. Read the 'when n doubles' column. Then add n log n and log n. Which growth would your collision check (all pairs) follow?
The plotter draws operation counts against n for log n, n, n log n and n², and a table gives each count and the factor it grows by when n doubles: about 1 extra step for log n, 2 for n, a little over 2 for n log n and 4 for n².
Figure 6.4 from “Breadth-first search: a queue explores a map”
Keep Breadth-first search selected and step through the first 20 expansions. Notice the 'rings' of equal move count. Then wall off the goal completely and watch what BFS does. Finally, add walls to make the path as long as you can.
The planner shows a 7 × 10 grid with a start on the left and a goal on the right, a wall in column 5 rows 1 to 5, and a rough patch. BFS expands cells in rings of increasing move count and returns a fewest-moves path around the end of the wall. Walling off the goal makes BFS expand every reachable cell and report no path.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Code Lab (Studio)
Count the comparisons made by linear and binary search on lists of 1,000 and 1,000,000 sorted numbers.
Open online - Nexus: Virtual Autonomous Rover (Nexus project)
Plan a path across a grid map with breadth-first search and count the cells it explored.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A sorted list holds 500 part numbers. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?
Answer: comparisons
Check it in “Halve it again: binary search”
2. Binary search runs on the unsorted list [40, 10, 30, 20] looking for 40. What happens?
- It finds 40
- It reports 'not found' even though 40 is there
- It sorts the list first
- It raises an error
Check it in “Halve it again: binary search”
3. A student writes 'while lo < hi:' instead of 'while lo <= hi:'. What goes wrong?
- Nothing
- When the range shrinks to one item, the loop stops without checking it, so that item can be missed
- The loop never ends
- It searches the list twice
Check it in “Halve it again: binary search”
4. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?
Answer: steps
Check it in “Count the steps before you time them”
5. One loop over n readings filters spikes; a second loop over n readings averages them. How many loop passes in total?
- n
- 2n
- n²
- n(n − 1)/2
Check it in “Count the steps before you time them”
6. Which list is in order from slowest-growing to fastest-growing?
- n, log n, n², n log n
- log n, n, n log n, n²
- n², n log n, n, log n
- 1, n², n, log n
Check it in “Big-O: the shape of growth”
7. What would change if BFS used a stack (pop the newest cell) instead of a queue?
- Nothing
- It would become depth-first search: it still explores, but the first path found need not be the shortest
- It would find shorter paths
- It would crash
Check it in “Breadth-first search: a queue explores a map”
8. The goal is completely surrounded by walls. What does BFS do?
- Loops forever
- Visits every cell reachable from the start, empties the queue and reports no path
- Walks through the wall
- Returns the start cell
Check it in “Breadth-first search: a queue explores a map”
Engineering applications
Look-up tables
Embedded systems often store calibration curves as sorted tables. Binary search finds the right segment in a handful of steps, fast enough to run every millisecond on a small microcontroller.
Path planning
Warehouse robots and game characters plan routes on grids. Breadth-first search finds the shortest route in steps; weighted versions add the cost of rough terrain or slow aisles.
Summary
- Binary search needs sorted data and about log2(n) comparisons; linear search needs up to n.
- Count operations as a function of n before timing; nested loops multiply, sequential loops add.
- Big-O keeps the fastest-growing term and drops constants: it describes shape, not seconds.
- Breadth-first search with a queue explores outwards and finds the fewest-step path on a grid.
Glossary
- Lists and indexing
- A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end.
- for loops and range
- A for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop.
- while loops
- A while loop repeats its body as long as its condition stays true, checking the condition before each pass.
Project: Measure the growth
Implement linear search, binary search and a nested-loop duplicate finder. Count operations for input sizes from 100 to 100,000, plot the counts on suitable axes, and check each curve against the Big-O you predicted.
Deliverables
- The three implementations with operation counters
- A plot with labelled axes and a caption
- Predicted and observed growth for each, with an explanation of any gap
References
- Thomas H. Cormen et al. (2009). Introduction to Algorithms, 3rd edition. MIT Press.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
7. Numerical methods
Many engineering equations have no tidy algebraic answer, so we hunt the answer numerically. Bisection traps a root between two points of opposite sign and halves the trap each step: slow but certain. Newton's method rides the tangent and converges very fast near a root, but can wander off when the slope is flat. On sampled data, finite differences estimate rates and the trapezoid rule estimates totals.
Figure 7.1. Trap the root, halve the trap (described in words)
Bisection on f(x) = x² − 2 starting from [1, 2]: midpoints 1.5, 1.25, 1.375 and 1.4375. After four halvings the root is trapped in [1.375, 1.4375], width 0.0625, around the true root 1.41421.
Explanation
7.1 Bisection: trap the answer, halve the trap
No formula gives the cable tension where a sag equation balances. But if you know one guess is too low and one too high, you can corner the answer to any accuracy you like.
Bracket, test, keep half
Pick a and b with f(a) * f(b) < 0. Compute the midpoint m. If f(m) has the same sign as f(a), the root is in [m, b]; otherwise it is in [a, m]. Repeat until the bracket is narrower than your tolerance.
Error you can predict
The error after k steps is at most (b − a)/2^(k+1) if you report the midpoint. That bound does not depend on the equation at all, so you can plan the computation before you run it. Each step gains one binary digit of accuracy (linear convergence).
When it fails
Bisection needs a sign change. A root where the curve only touches zero (like x² at 0) has no sign change and can't be bracketed. A discontinuity (like 1/x) can fake a sign change with no root. Always check f(a)·f(b) < 0 first and plot f if unsure.
Derivation: How many bisection steps for a given accuracy?
Start with a bracket [a, b] where f(a) and f(b) have opposite signs, so a continuous f must cross zero somewhere inside (the intermediate value theorem).
Each step tests the midpoint m = (a + b)/2 and keeps the half where the sign still changes. The new bracket has width (b − a)/2.
After k steps the width is w_k = (b − a)/2^k. The root is always inside, so the midpoint is within w_k/2 of it.
To guarantee w_k ≤ tol we need 2^k ≥ (b − a)/tol, so k = ⌈log₂((b − a)/tol)⌉.
Example: [0, 2] to a width of 10⁻⁶ needs ⌈log₂(2 × 10⁶)⌉ = ⌈20.93⌉ = 21 steps. Each extra decimal place costs about 3.3 more steps.
Common mix-ups
Stop when f(midpoint) == 0.
✓ In floating point that may never happen. Stop when the bracket is narrower than a tolerance.A sign change always means a root.
✓ Only for a continuous function. 1/x changes sign across 0 but has no root.
7.2 Newton's method: ride the tangent
Bisection needs about 20 steps for six decimal places. Newton's method often needs four. What's the catch?
Fast when close
From a good starting guess, Newton's method converges quadratically: the number of correct digits roughly doubles each step. For x² − 2 from 1, four steps give about 12 correct digits, where bisection on [0, 2] would need about 40.
It needs the derivative
You must supply f′(x), worked out by hand or estimated numerically. If f′(x_k) = 0 the tangent is flat and never crosses zero: the method can't continue. Guard against it and cap the number of steps.
It can run away
If the start is far from the root, or the function flattens out, the tangent can throw the next guess further away. arctan x from x₀ = 1.5 diverges. Engineers often bracket first with bisection, then switch to Newton once close, or reject any Newton step that leaves the bracket.
Derivation: Where the Newton update comes from
Near a guess x_k, replace the curve by its tangent line: y ≈ f(x_k) + f′(x_k)·(x − x_k).
Find where that line crosses zero: 0 = f(x_k) + f′(x_k)·(x − x_k).
Solve for x: x_{k+1} = x_k − f(x_k)/f′(x_k). This needs f′(x_k) ≠ 0.
For f(x) = x² − c, f′(x) = 2x, so x_{k+1} = x_k − (x_k² − c)/(2x_k) = (x_k + c/x_k)/2: average the guess with c divided by the guess.
Near a simple root the error obeys e_{k+1} ≈ C·e_k², so an error of 10⁻³ becomes about 10⁻⁶, then 10⁻¹². That's quadratic convergence.
Common mix-ups
Newton's method always finds the nearest root.
✓ It can jump to a different root, or diverge, depending on the starting guess.If a few steps look like they are settling, the answer is right.
✓ Check |f(x)| is small and the change between steps is below tolerance, and cap the steps.
7.3 Speed from position, distance from speed: calculus on samples
Your encoder gives position every 10 ms. Differentiate to get speed and the plot turns into hair. Integrate speed to get distance and it's beautifully smooth. Why the difference?
Derivatives from differences
Forward difference: (x[i+1] - x[i]) / h, an estimate of the speed between two samples. Central difference: (x[i+1] - x[i-1]) / (2 * h), centred on sample i and usually more accurate for smooth data (its error shrinks like h² rather than h).
Integrals from trapezia
Join neighbouring samples with straight lines and add the areas: h * (v[0]/2 + v[1] + ... + v[-2] + v[-1]/2). For speed samples this gives distance; for power samples, energy. Its error shrinks like h² for smooth data.
Noise changes the advice
On clean data, smaller h is always better. On noisy data, differencing divides the noise by h, so too-small steps make speed estimates useless. Integrate when you can, smooth before you differentiate, and always state the sample interval in your report.
Derivation: Why differences amplify noise
Each reading is x_i + n_i, where the noise n_i is at most ε in size.
Forward difference: ((x_{i+1} + n_{i+1}) − (x_i + n_i))/h = (x_{i+1} − x_i)/h + (n_{i+1} − n_i)/h.
The noise term can be as large as 2ε/h. Halving h doubles it.
The trapezium rule multiplies each reading by h and adds them, so noise enters as h·Σn_i. Random noise partly cancels in the sum: integration smooths, differentiation sharpens.
So choose h large enough that 2ε/h is acceptable, or smooth the readings first (for example with a moving average), or use a central difference over 2h.
Common mix-ups
Sampling faster always gives a better speed estimate.
✓ With noise, faster sampling makes simple differences noisier. Filter or difference over longer windows.The trapezium rule is exact.
✓ Its error shrinks like h², and it is exact only for straight-line segments.
Examples to try
Worked solutions are in the interactive chapter online.
Bisection: trap the answer, halve the trap: example 1
Find √2 as the root of x² − 2 on [0, 2] to a width of 10⁻⁶.
Newton's method: ride the tangent: example 1
Newton's method with a step limit and a flat-slope guard, compared with the true root.
Speed from position, distance from speed: calculus on samples: example 1
Differentiate and integrate clean and noisy samples of x = 0.2t² (metres).
Interactive figures, in words
Figure 7.2 from “Bisection: trap the answer, halve the trap”
Choose x² − 2 and Bisection. Step ten times and watch the lavender bracket and the error column. Then move the ends so f(a) and f(b) have the same sign. Finally try cos x − x: does the bracket still halve at the same rate?
The stepper plots f(x) = x² − 2 on 0 to 3 with a lavender bracket. Each bisection step halves the bracket: [0, 2], [1, 2], [1, 1.5], [1.25, 1.5] and so on, closing in on 1.41421. With ends that give f the same sign, the stepper reports that bisection cannot start.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Equation Lab: Roots (Equation Lab exploration)
Find the root of x² − 2 with bisection and with Newton's method and count the steps each needs for six decimal places.
Open online - Code Lab (Studio)
Estimate speed from a list of position samples with central differences, then add noise and watch the estimate degrade.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A cable tension must satisfy f(x) = x**2 - 11 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 2? Give 4 decimal places.
Answer:
Check it in “Bisection: trap the answer, halve the trap”
2. Bisection starts from the bracket [0, 2] and stops once the bracket width is at most 0.05. What is the smallest number of steps that guarantees this?
Answer: steps
Check it in “Bisection: trap the answer, halve the trap”
3. f(x) = (x − 1)² on [0, 3]. Why can't bisection start?
- The root is outside the bracket
- f(0) and f(3) are both positive, so there is no sign change to trap
- Squares can't be computed numerically
- The bracket is too wide
Check it in “Bisection: trap the answer, halve the trap”
4. A microcontroller finds a vector length L = √12 with Newton's method on f(x) = x**2 - 12, using x = x - (x**2 - 12) / (2*x). Starting from x0 = 1, what is x after 2 iterations? Give 4 decimal places.
Answer:
Check it in “Newton's method: ride the tangent”
5. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?
- It converges to 2
- It converges to −2
- It fails: f′(0) = 0, so the update divides by zero
- It converges slowly
Check it in “Newton's method: ride the tangent”
6. Which statement compares bisection and Newton fairly?
- Newton is always better
- Bisection is guaranteed given a sign change but slow; Newton is much faster near a root but can fail from a poor start
- Bisection needs the derivative
- They converge at the same rate
Check it in “Newton's method: ride the tangent”
7. A linear-axis encoder logs position every 0.1 s: x = [11, 20, 29, 32, 38, 45] mm. Estimate the speed at sample index 4 using a forward difference (x[i+1] - x[i]) / h, in mm/s.
Answer: mm/s
Check it in “Speed from position, distance from speed: calculus on samples”
8. A rover logs wheel speed every 2 s: v = [1, 1, 5, 5.5] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?
Answer: m
Check it in “Speed from position, distance from speed: calculus on samples”
Engineering applications
Solving circuits
Circuit simulators solve the nonlinear equations of diodes and transistors with Newton's method at every time step, falling back to safer, slower steps when the tangent misleads.
Distance from speed
A data logger records speed ten times a second. The trapezoid rule adds those samples into the distance travelled, and the same idea turns a power log into energy used.
Summary
- Bisection needs a sign change; each step halves the bracket, so the error bound is known in advance.
- Newton's method uses x − f(x)/f'(x); it is fast near a root but fails when f'(x) is near zero.
- Finite differences estimate derivatives from samples; noise is amplified by small steps.
- The trapezoid rule adds the areas of thin trapezoids to estimate an integral from samples.
Glossary
- Derivative (rate of change)
- The derivative of a quantity is its instantaneous rate of change: the gradient of its graph at a point.
- Integral as accumulated area
- An integral adds up a rate over time: the area under a rate graph gives the total accumulated amount.
- Floating-point rounding and comparison
- Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.
- The math module
- Python's built-in math module provides constants such as pi and e and functions such as sqrt, sin, cos, atan2, log10, hypot, radians and degrees.
Project: A root-finder you trust
Write bisection and Newton's method as functions with a tolerance and a maximum number of iterations. Use them to find the voltage at which an LED model draws 20 mA, compare the iteration counts, and show one starting point where Newton fails and bisection does not.
Deliverables
- Both functions with stopping rules and tests
- A table of iterations to reach the tolerance
- The failing Newton case, explained
References
- Jaan Kiusalaas (2013). Numerical Methods in Engineering with Python 3. Cambridge University Press.
- Richard L. Burden and J. Douglas Faires (2011). Numerical Analysis, 9th edition. Brooks/Cole.
8. Simulating dynamic systems
A cooling mug, a charging capacitor and a falling parachutist all obey a rate equation: how fast something changes depends on where it is now. Euler's method steps forward in small time slices, and the step size controls the error and even whether the answer blows up. Fit the model's parameter to measurements, then validate it on data you did not fit, and state the limits of the model honestly.
Figure 8.1. Halve the step, roughly halve the error (described in words)
Euler's method for dy/dt = −y from y(0) = 1, evaluated at t = 1: step 0.5 gives 0.25 (error 0.1179), step 0.25 gives 0.3164 (error 0.0515), step 0.125 gives 0.3436 (error 0.0243). The exact value is 0.3679; the error roughly halves each time the step halves.
Explanation
8.1 Rate equations and exponential decay
A hot drink cools fastest when it is hottest. A capacitor discharges fastest when it is fullest. Write that sentence as an equation and the solution writes itself.
Writing the equation
RC discharge: the current through R is V/R and it drains the capacitor: C·dV/dt = −V/R, so dV/dt = −V/(RC), τ = RC. Newton's cooling: heat flow is proportional to the temperature difference, so dT/dt = −k(T − Tₐ). Both: rate ∝ distance from equilibrium.
The time constant
τ (seconds or minutes) sets the speed. After 1τ, 37% of the initial difference remains; after 3τ, 5%; after 5τ, under 1%. Engineers call a first-order system 'settled' after about 4–5τ. For R = 10 kΩ and C = 100 µF, τ = 1 s.
Why the solution must be exponential
Only one family has a rate proportional to its value: e^(kt), from week 3's chain rule. So once you see 'rate ∝ amount', you can write the exponential solution straight away, then fit k (week 9). The equation also gives the units: k is per second, so kt has no units, as an exponent must.
Derivation: Solving dy/dt = −ky
Model: the rate of decrease is proportional to the amount: dy/dt = −k·y, k > 0, with y(0) = y₀.
Separate variables (for y > 0): (1/y) dy = −k dt.
Integrate both sides: ln y = −kt + C.
Exponentiate: y = e^C·e^(−kt). At t = 0, y = e^C = y₀, so y(t) = y₀·e^(−kt).
Check by differentiating: dy/dt = y₀·(−k)·e^(−kt) = −k·y ✓.
Time constant τ = 1/k: y(τ) = y₀e⁻¹ ≈ 0.368y₀. Half-life: e^(−kt) = ½ gives t½ = ln 2/k = τ·ln 2.
Cooling: let u = T − Tₐ; then du/dt = dT/dt = −k·u, so T(t) = Tₐ + (T₀ − Tₐ)e^(−kt).
Common mix-ups
After one time constant the quantity has halved.
✓ After τ it is at 37%; it halves after τ·ln 2 ≈ 0.69τ.The drink cools towards 0 °C.
✓ It cools towards the room temperature Tₐ: only the difference decays.
8.2 Euler's method and step-size error
Most differential equations have no formula solution. So computers cheat: take the slope now, step forward a little, repeat. When does that cheating go badly wrong?
The method
Know the state yₙ at time tₙ. Compute the slope f(tₙ, yₙ) from the equation. Step: yₙ₊₁ = yₙ + h·f(tₙ, yₙ), tₙ₊₁ = tₙ + h. Repeat. That is all, and it is exactly how the week 4 forward difference is used in reverse.
Accuracy: first order
Euler's global error ∝ h. To get ten times more accurate, take ten times more steps. Check any simulation by halving h: if the answer changes noticeably, the step was too large. Better methods (such as Runge–Kutta) reach error ∝ h⁴ for a little more work per step.
Stability: a separate danger
Accuracy and stability are different. Too large a step can make a decaying system grow without limit. For dy/dt = −y/τ the limit is h < 2τ, and smooth results need h < τ. Fast processes (small τ) therefore force small steps even when you only care about slow ones.
Derivation: Euler's step factor, its error and its stability limit
For dy/dt = −k·y, one Euler step gives yₙ₊₁ = yₙ + h·(−k·yₙ) = (1 − kh)·yₙ.
The exact solution multiplies by e^(−kh) = 1 − kh + (kh)²/2 − … each step. The difference per step is about (kh)²/2: the local error ∝ h².
To reach a fixed time T takes T/h steps, so the errors add to about (T/h)·h² ∝ h: the global error is first order. Halve h, halve the error.
After n steps yₙ = y₀(1 − kh)ⁿ. This decays only if |1 − kh| < 1, that is 0 < kh < 2, or h < 2τ.
For 1 < kh < 2 the factor is negative: the numerical solution overshoots zero every step while shrinking. For kh > 2 it grows without bound: numerical instability, not physics.
Common mix-ups
If a simulation blows up, the physical system is unstable.
✓ It may be numerical instability from too large a step. Halve h and see if it persists.A stable simulation is an accurate one.
✓ Stable only means it does not explode. Accuracy needs a convergence check.
8.3 Falling with drag: terminal velocity
Drop a paper cone and it stops speeding up within a second. Gravity has not switched off. What is it fighting, and what speed does it settle at?
Same equation, new physics
Falling with linear drag is a first-order system approaching equilibrium v_T with time constant τ = m/b. After τ the object has reached 63% of v_T, after 3τ about 95%. For m = 0.2 kg and b = 0.1 kg/s: v_T = 19.6 m/s and τ = 2 s.
Linear or quadratic drag?
Drag ∝ v (linear) suits small, slow objects in thick fluids: dust, a sensor sinking in oil. Drag ∝ v² (quadratic) suits most everyday objects in air: a paper cone, a parachutist. Quadratic drag gives v = v_T·tanh(gt/v_T): the same start and end, but a sharper approach. Which you choose is an assumption to test against data.
Distance fallen
Integrate the velocity: x(t) = v_T·[t − τ(1 − e^(−t/τ))]. After a few τ the object falls almost exactly v_T metres each second, offset by v_T·τ: the distance 'lost' to the initial acceleration.
Derivation: Solving m·dv/dt = mg − bv
Free-body diagram (downwards positive): weight mg down, drag bv up. Newton's second law: m·dv/dt = mg − bv.
Terminal velocity: when dv/dt = 0, v_T = mg/b.
Rewrite: dv/dt = (mg − bv)/m = −(b/m)(v − v_T). Let τ = m/b and u = v − v_T.
Then du/dt = −u/τ: exactly last lesson's decay equation, with u(0) = −v_T (dropped from rest).
So u = −v_T·e^(−t/τ) and v(t) = v_T·(1 − e^(−t/τ)).
Check: v(0) = 0; v → v_T as t → ∞; dv/dt at t = 0 is v_T/τ = g, free fall at the start, as it must be.
Common mix-ups
At terminal velocity there is no force on the object.
✓ Weight and drag are both there; they are equal and opposite, so the net force is zero.Heavier objects always fall faster.
✓ In a vacuum they fall together. With drag, heavier objects of the same shape reach a higher terminal velocity.
8.4 Validating a model and stating its limits
Your cooling model fits the first 30 minutes beautifully. Does it predict the next 30? The only honest way to find out is to keep some data back.
Verification and validation
Verification: does the code solve the equation correctly? Check against an exact solution and by halving the step (week 8). Validation: does the equation describe the real system? Check against data the model was not tuned on. A perfectly verified model of the wrong physics is still wrong.
Hold-out testing
Split the data before fitting: fit on one part, then predict the other. Report the error on the held-out part, with units: RMS = √(mean of squared residuals), or percentage error |model − data|/data. For time series, hold out the later part: that is what a prediction actually has to do.
Assumptions and their effects
Cooling model: well-mixed liquid (one temperature), constant room temperature, constant k (in fact convection and radiation make k vary with temperature), no evaporation (which speeds early cooling). Drag model: linear drag (often quadratic in air), still air. For each, say which way it pushes the prediction and when it matters.
Common mix-ups
A low error on the fitting data validates a model.
✓ Only error on data not used for fitting tests whether the model generalises.Listing limitations weakens a report.
✓ Stating limits honestly is what makes the remaining claims trustworthy.
Examples to try
Worked solutions are in the interactive chapter online.
Rate equations and exponential decay: example 1
R = 10 kΩ, C = 100 µF, V(0) = 9 V. Find τ and V at 2 s.
Euler's method and step-size error: example 1
dV/dt = −V/2, V(0) = 5 V, h = 0.5 s. Take two Euler steps.
Falling with drag: terminal velocity: example 1
m = 0.2 kg, b = 0.1 kg/s. When does it reach 95% of terminal velocity, and how fast is it then?
Validating a model and stating its limits: example 1
Held-out residuals are 1, −1, 2 and −2 °C. What is the RMS error?
Interactive figures, in words
Figure 8.2 from “Rate equations and exponential decay”
Choose the capacitor data. Turn on the log view: the points should lie on a straight line. Adjust k until the model line matches, then press Best fit. Read τ and the half-life. Why is ln(V) straight when V is curved?
In the decay-fit lab the capacitor readings fall from 9 V towards zero. In the log view, ln V against time is a straight line whose slope is −k; the best fit gives k close to 0.45 per second, so τ ≈ 2.2 s and a half-life of about 1.5 s. The readout states k, τ, half-life and the RMS error.
Figure 8.3 from “Euler's method and step-size error”
Start with τ = 2 and h = 0.5: read the error table and its ratio. Now try h = 1, 2, 2.5 and watch the regime change from smooth, to overshooting, to oscillating forever, to unstable. Change τ: does the boundary move with h/τ?
The Euler lab plots the exact exponential decay with Euler's points. With τ = 2 and h = 0.5 the points track the curve slightly low and the error halves when h halves. At h = 3 they zigzag about zero while shrinking; at h = 4 they oscillate with constant size; at h = 5 they zigzag and grow. The readout names the regime from h/τ.
Figure 8.4 from “Falling with drag: terminal velocity”
Set m = 0.2 kg and b = 0.1 kg/s. Read v_T and τ. Slide the time to τ, 2τ and 3τ: what fraction of v_T has it reached each time? Double the mass, then double b. Finally compare quadratic drag: same terminal speed, different approach.
The drag lab plots speed against time: a dotted free-fall line v = gt, the linear-drag curve rising and flattening at the terminal velocity (a dashed horizontal line), and optionally a quadratic-drag curve with the same terminal speed that approaches it more sharply. For m = 0.2 kg and b = 0.1 kg/s, v_T = 19.6 m/s and τ = 2 s.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Equation Lab: First-order systems (Equation Lab exploration)
Step a decay equation with Euler at three step sizes and compare each with the exact solution.
Open online - Simulation OS: RC charging and discharging (Simulation OS experiment)
Read the capacitor voltage after one time constant and check it against your own Euler simulation.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A cooling temperature difference halves every 12 minutes. What is its time constant τ, in minutes?
Answer: min
Check it in “Rate equations and exponential decay”
2. What percentage of the initial value remains after 5 time constants?
Answer: %
Check it in “Rate equations and exponential decay”
3. A falling object with linear drag obeys dv/dt = g − v/τ with g = 9.81 m/s², τ = 0.5 s and v(0) = 0. Take 5 Euler steps of h = 0.2 s. What is the Euler estimate of v, in m/s?
Answer: m/s
Check it in “Euler's method and step-size error”
4. For dy/dt = −y/τ with τ = 2 s, what is the largest Euler step (in seconds) that does not blow up?
Answer: s
Check it in “Euler's method and step-size error”
5. You halve Euler's step size (staying well inside the stable range). Roughly what happens to the error at a fixed time?
- It halves
- It quarters
- It is unchanged
Check it in “Euler's method and step-size error”
6. An object of mass 0.05 kg is dropped from rest with linear drag b = 0.4 kg/s (g = 9.81 m/s²). Its speed is v(t) = v_T·(1 − e^(−t/τ)) with v_T = mg/b and τ = m/b. What is v at t = 3 s, in m/s?
Answer: m/s
Check it in “Falling with drag: terminal velocity”
7. Held-out residuals are 1, −1, 2 and −2 °C. What is the RMS error, in °C?
Answer: °C
Check it in “Validating a model and stating its limits”
8. You halve Euler's step and the simulated temperature barely changes. What have you shown?
- The model is validated
- The numerical solution is verified (converged), not that the model matches reality
- The data are correct
Check it in “Validating a model and stating its limits”
Engineering applications
Thermal design
Before building an enclosure, engineers simulate how fast electronics heat up and cool down. A simple rate model, fitted to one measured warm-up curve, predicts whether a fan is needed.
Trust, then verify
A simulation that matches the data it was fitted to proves little. Validating against a separate test, and reporting the error, is what turns a model into evidence.
Summary
- A rate equation says how fast a quantity changes from its current value: dy/dt = −y/τ decays exponentially.
- Euler's method steps y(n+1) = y(n) + h·f(y(n)); its error shrinks roughly in proportion to h.
- Too large a step can make Euler unstable even when the real system is stable.
- Verification checks the code solves the equations; validation checks the equations match reality.
Glossary
- Exponential growth and decay
- A quantity decays exponentially when its rate of decrease is proportional to how much is left, giving y = y0 × e^(−t/τ).
- First-order system and time constant
- A first-order system responds to a step by approaching its new value exponentially; its time constant τ is the time to cover 63.2 % of the change.
- RC time constant
- When a capacitor charges or discharges through a resistor, the voltage changes exponentially with time constant τ = R × C.
- Derivative (rate of change)
- The derivative of a quantity is its instantaneous rate of change: the gradient of its graph at a point.
Project: A cooling model, fitted and validated
Use a recorded or provided cooling curve for a cup of water. Fit the time constant from part of the data, simulate it with Euler at a step you justify, and validate the model on the rest of the data. Report the RMS error and one honest limitation.
Deliverables
- The fitted time constant with working
- A plot of data and model, with the fitting and validation sections marked
- The RMS error and a stated limitation of the model
References
- Jaan Kiusalaas (2013). Numerical Methods in Engineering with Python 3. Cambridge University Press.
- Richard L. Burden and J. Douglas Faires (2011). Numerical Analysis, 9th edition. Brooks/Cole.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
Known limitations
- Not yet tested by a person using a screen reader; only automated structure checks have run.
- Some interactive lesson diagrams need a pointer or keyboard and a recent browser; their text alternatives carry the same idea without the interaction.
- Mathematics is written as plain text (for example x^2 and sqrt(x)), like the School lessons, not typeset notation.