P00.07 ยท Lesson 07 of 15
Testing Engineering Code
A calculation you have not tested is a guess with a decimal point.
Build it pytest suite with tolerance-based assertions
- Learning outcomes
- Explain, with a worked binary example, why two floating-point results that "should" be equal usually are not, and choose a relative or absolute tolerance for a comparison.
- Implement a small lift-and-drag coefficient calculator that validates its inputs and raises
ValueErroron unphysical values. - Write a pytest suite that uses
pytest.approx,numpy.testing.assert_allclose,pytest.raises,pytest.mark.parametrize, limiting cases and a regression test against a stored reference table. - Decide, for a given failing test, whether the code, the test or the stored reference is wrong.
- Prerequisites
P00.01,P00.03; skill check: can write a Python function with a docstring and run it from the command line; can rearrange for any one variable.- Engineering question
Can we trust the lift-to-drag ratio our drag-polar code reports for a light aircraft, to within 0.01 %, after every future edit to that code?
Full lesson specification (11 more items)
- Assumptions and limits
Parabolic drag polar with constant and ; incompressible flow (Mach below about 0.3); no stall, so is unbounded in the model. The floating-point discussion assumes IEEE 754 double precision (NumPy
float64).- Analytical work
Derive the lift coefficient from the lift equation; derive and from the parabolic polar; bound the rounding error of a repeated subtraction.
- Computational deliverable
starter/main.py:dynamic_pressure,lift_coefficient,drag_coefficient,drag_polar,lift_to_drag,max_lift_to_drag,polar_table,is_close,rocket_mass_closed_form,rocket_mass_stepwise. Tests prove: analytic values to 1e-12 relative, limiting cases (, , ), input validation, the optimum beats every sampled point, and agreement with a stored table to 2e-7.- Practical activity
computational experiment: measure how rounding error in a stepwise rocket-mass loop grows with the number of steps and with the step size, and compare with the bound from part 2.
- Equipment
None
- Safety
None beyond normal computer use
- Evidence
Your completed
main.py, the passing test run (pytest -voutput), the drift-versus-steps table and plot from part 4, and a half-page note on which tolerance you chose for each test and why.- Assessment
assessments/phase-00/grading-rubric.md; competencies 2 (analytical), 3 (computational) and 4 (interpretation); pass when all public tests pass and the tolerance note defends every tolerance with a number.- References
@pytest-getstarted"Get Started": "Create your first test", "Assert that a certain exception is raised", "Compare floating-point values with pytest.approx", "Group multiple tests in a class" (required-free);@numpy-userguideNumPy reference,numpy.testing(assert_allclose) (supplementary-free).- Extensions
โ Add a
hypothesis-style property test by hand: generate 1000 random pairs with a seedednumpy.random.default_rngand check the optimum property for each. โ Replace the parabolic polar with a tabulated polar read from a file and make the regression test cover interpolation.- Time
unmeasured
1. The engineering problem
You have written a drag-polar calculator. It takes a lift coefficient and returns a drag coefficient, and from those two numbers a lift-to-drag ratio . Someone on your team will use to size the fuel tanks of a light aircraft: a 1 % error in is a 1 % error in range. Next month a teammate will "tidy up" the code, and the month after that you will add compressibility corrections. How do you know the number is still right?
The answer in professional engineering software is the same as the answer in a wind tunnel: you do not trust a reading, you check it against a reference, and you repeat the check every time something changes. In code the reference is a test: a short function that runs your code on a case whose answer you know by other means and fails loudly if the two disagree. A test suite is a set of such tests run together by a tool called pytest. The success criterion for this lesson is a suite that passes against a correct calculator, fails against a broken one, and tells you which property broke.
What goes wrong without it is not hypothetical. Untested unit conversions lost the Mars Climate Orbiter in 1999 (you met that story in P00.05); untested sign conventions regularly invert control surfaces in simulators; and a test that compares two floating-point numbers with == will pass on one machine and fail on another for reasons that have nothing to do with physics. The centre of this lesson is that last trap: why exact float equality fails and what to assert instead.
2. Understand and derive
2.1 The calculator we are testing
Define a term each time it appears. The dynamic pressure is the kinetic energy per unit volume of the oncoming air:
with air density in kg/mยณ and true airspeed in m/s. Units check: . Lift and drag are forces in newtons; dividing them by and the reference wing area (mยฒ) gives the dimensionless lift coefficient and drag coefficient:
For a whole aircraft at low speed, depends on through the parabolic drag polar
where is the drag at zero lift (skin friction and form drag), is the wing aspect ratio and the Oswald efficiency factor. The model assumes the induced drag is exactly quadratic in and that does not change with speed; it fails near stall (where stops growing) and above Mach 0.3 (where compressibility raises ). We use , (roughly , ) as the lesson's default.
Best lift-to-drag ratio. Write . Differentiate with the quotient rule and set the result to zero:
At the optimum the induced drag equals , so and
For the default polar: and . Those two numbers are analytic references: a test can compare the code against them. Better still, a test can check the property "no sampled point on the polar beats the analytic optimum", which stays true for every and does not depend on remembering 15.81.
2.2 Why 0.1 + 0.2 != 0.3
A float64 stores a number as with 52 bits for the fraction . Only fractions whose denominators are powers of two are exact. One tenth is , a repeating binary fraction, so the computer stores the nearest representable value, about . The same happens to 0.2 and 0.3. Add the stored 0.1 and 0.2, round the sum to 52 bits, and you get , while the stored 0.3 is . They differ by one ulp (unit in the last place, the gap between neighbouring floats), which is near 0.3. So 0.1 + 0.2 == 0.3 is False, and no amount of care in your physics will change that.
The same thing happens in engineering code constantly. is exactly 1531.25 in decimal, but 1.225 is not exact in binary (it is stored as ), so the product may land one ulp away from the literal 1531.25. In this particular case the two roundings happen to cancel and Python returns exactly 1531.25; change the density to 1.2 or the speed to 51 and they may not. You cannot tell in advance without doing the binary arithmetic, which is exactly why == is the wrong tool. A loop that subtracts a propellant mass of 0.1 kg per step a hundred times does not land on exactly kg: it lands on 39.99999999999986 for .
How large is the drift? Each floating-point operation rounds its exact result to the nearest float, which introduces a relative error of at most (half an ulp; np.finfo(float).eps is ). After subtractions on a quantity of size about , the accumulated error is bounded by roughly , and in practice is smaller because errors partly cancel. For kg and : bound kg. We will see about kg. Physically meaningless, numerically fatal to ==.
2.3 What to assert instead: tolerances
Two numbers and are close if
- The relative tolerance says "agree to this many significant figures".
rel_tol = 1e-12means agreement to 12 figures, appropriate when both numbers come from a few arithmetic operations on exact inputs. - The absolute tolerance is needed when the true answer is zero or nearly zero, because a relative tolerance on zero is zero:
is_close(0.0, 1e-12)with any relative tolerance alone isFalse.
pytest.approx(x, rel=..., abs=...) implements this for scalars and small sequences (default rel=1e-6, abs=1e-12). numpy.testing.assert_allclose(actual, desired, rtol=..., atol=...) does it element-wise for arrays and prints the worst mismatch when it fails (its rule is |a - d| <= atol + rtol * |d|, a slightly different but equivalent-in-spirit form; note it is relative to desired, so put the reference second). Choosing the tolerance is an engineering decision, and the rule is: as tight as the arithmetic allows, and justified by a number. For an exact formula evaluated once, 1e-12 relative. For a value stored to 8 significant figures, 2e-7 relative. For a value that depends on a numerical method, the method's error estimate.
The number line near 0.3, drawn to scale in ulps, makes the situation plain:
stored 0.3 stored 0.1 + stored 0.2
| |
...--------+-----------------+-------------------+--------...
0.29999999999999998890 (one float gap, 0.30000000000000004441
5.55e-17, no
value in between)
There is no float between those two ticks, so no amount of extra computation can make the sum "land" on 0.3. A tolerance of a few ulps (relative ) accepts it; == never will.
Worked example: choosing a tolerance for . We want to test dynamic_pressure(1.225, 50.0) against the hand value 1531.25 Pa. Three operations are involved (store 1.225, multiply by 0.5, multiply by 2500), each contributing at most half an ulp of relative error, so the arithmetic bound is about relative, or Pa. Any tolerance above that passes a correct implementation. Now ask what wrong implementation we need to catch: a dropped factor (100 % error), a density typed as 1.255 (2.4 %), a speed in knots (165 %). The smallest of those is 2.4 %. A tolerance of rel=1e-12 is a million times above the arithmetic floor and ten billion times below the smallest bug: comfortable on both sides. That two-sided argument, floor from the arithmetic, ceiling from the smallest bug worth catching, is how every tolerance in this lesson is chosen, and it is what the tolerance note you submit must contain.
2.4 The five kinds of test in this lesson
- Analytic value. Compare with a hand calculation: Pa.
- Limiting case. as ; as ; independent of when . Limiting cases catch sign and factor errors that an analytic value at one point can miss.
- Invalid input raises. A negative density or a zero wing area is a bug upstream; the function must refuse with
ValueError, not returninfornan. Silence is how bad numbers travel. - Parametrized test. The same property checked for several polars, so the test does not accidentally pass only for the default numbers.
- Regression test. A table of outputs generated once by a reviewed version of the code and stored in the test file. It does not prove the code is right; it proves the code has not changed. When it fails, you must decide whether the change was intended.
3. Build the computational model
Open starter/main.py. Every function has a docstring that says what to return and when to raise. Work top to bottom; run pytest curriculum/phase-00/lesson-07-testing-engineering-code -q after each function and watch failures turn into passes.
Step 1: input checks and dynamic pressure
Write two small helpers and use them everywhere. They accept scalars or arrays.
import numpy as np
def _check_positive(name: str, value) -> None:
arr = np.asarray(value, dtype=float)
if not np.all(np.isfinite(arr)):
raise ValueError(f"{name} must be finite, got {value!r}")
if np.any(arr <= 0.0):
raise ValueError(f"{name} must be strictly positive, got {value!r}")
def dynamic_pressure(rho, v):
_check_positive("rho", rho)
_check_nonnegative("v", v) # same pattern, allows zero
return 0.5 * np.asarray(rho, dtype=float) * np.asarray(v, dtype=float) ** 2
Two design choices to notice. np.asarray(..., dtype=float) makes the function work for a single float and for a whole array of speeds (vectorization, from P00.03). And the check for finite comes first: nan <= 0.0 is False, so a NaN would otherwise slip through a positivity test.
Step 2: coefficients and the polar
lift_coefficient divides by , so it must insist on strictly positive and (zero would divide by zero). drag_coefficient additionally rejects negative drag. drag_polar rejects negative or and a non-finite . max_lift_to_drag is the two formulas from part 2; because it divides by it requires both strictly positive. polar_table stacks three columns with np.column_stack.
Step 3: your own is_close
Implement the rule in 2.3 yourself before using the library versions; the point is to see that there is nothing magic inside pytest.approx.
import math
def is_close(a, b, rel_tol=1e-9, abs_tol=0.0):
if rel_tol < 0.0 or abs_tol < 0.0:
raise ValueError("tolerances must be non-negative")
if math.isnan(a) or math.isnan(b):
return False
if a == b: # catches equal infinities
return True
if math.isinf(a) or math.isinf(b):
return False
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
The test compares your function against math.isclose on a grid of cases, including the near-zero case where only an absolute tolerance can pass.
Step 4: the rocket-mass drift demonstration
rocket_mass_stepwise subtracts mdot * dt in a loop and records every intermediate mass; rocket_mass_closed_form returns directly. Both raise when the propellant would run out. The loop version is how a time-marching simulation depletes mass in Phase 05, and the test shows that it drifts from the closed form by a few kg while remaining within tolerance.
Step 5: read the test file as a worked example
tests/test_main.py is part of the lesson. Read it top to bottom and find each of the five kinds of test from 2.4. Note the comment above REFERENCE_POLAR: the table was produced once and its tolerance (rtol=2e-7) is justified by the 8 significant figures it was stored with.
Verify
- Analytic case:
test_dynamic_pressure_analytic_valueand the optimum property intest_max_lift_to_drag_is_the_maximum(k C_L^{*2} = C_{D0}to 1e-12). - Limiting cases:
test_dynamic_pressure_limits_and_scaling(, , ),test_drag_polar_limiting_cases(, , , evenness in ). - Conservation-like property:
test_coefficients_round_triprecovers the input force from the coefficient, andtest_rocket_mass_stepwise_drifts_but_stays_within_tolerancechecks that the drift is bounded by and that mass never increases. - Error plot: part 4 below.
Compare
Run the same comparison with the library tools: math.isclose, pytest.approx and numpy.testing.assert_allclose all implement the tolerance rule of 2.3, with different defaults. math.isclose defaults to rel_tol=1e-9, abs_tol=0; pytest.approx to rel=1e-6, abs=1e-12; assert_allclose to rtol=1e-7, atol=0. The defaults differ by three orders of magnitude, which is one more reason to state your tolerance explicitly in every assertion.
4. Experiment at home, or investigate real data
Mode: computational experiment. Measure how the rounding drift of the stepwise mass depletion grows, and compare with the bound from 2.2.
- Keep kg and the total burn kg fixed.
- For steps, set and compute
drift = abs(rocket_mass_stepwise(...)[-1] - rocket_mass_closed_form(m0, mdot, t_end)). - Record
n,drift, and the boundn * np.finfo(float).eps / 2 * m0in a table. Write down your prediction first: does the drift grow like , like , or not at all? - Plot drift and bound against on log-log axes (
ax.loglog), save todrift_vs_steps.png. - Repeat with
mdot * dtchosen so that the step is exactly representable in binary (for example 0.125 kg). What happens to the drift and why?
Raw data format: a CSV with columns n, dt_s, drift_kg, bound_kg, one row per .
5. Validate and improve
Put the three things side by side: the analytic bound , the measured drift, and the tolerance you chose in the test (rtol=1e-12). Before you ran it you may have predicted growth from "random" rounding errors cancelling. The measurement says otherwise: with kg the drift is kg at , at and at , a log-log slope close to 1, and only a factor of two to five below the bound. The reason is that the subtracted step mdot * dt carries the same representation error every time it is used, so the errors have the same sign and add; they are systematic, not random. "Rounding errors cancel" is an assumption, and here it fails. Write that discrepancy down and explain it; "numerical noise" is not an explanation.
The consequence for the test: at the drift of kg on 40 kg is relative, so a rtol=1e-12 assertion would fail even though the code is correct. That is the lesson's central judgment: a tolerance is a claim about the arithmetic, and it must be re-derived when the arithmetic changes. The right fix is to loosen the tolerance with a reason written in the test (for example rtol = 10 * n * eps), not to switch to ==, and not to loosen it to 1e-3 "to be safe", which would hide a real factor-of-two bug in the next edit.
Explain the step-0.125 result in your note: a step that is a dyadic rational is represented exactly, and so is every partial sum while the mass stays within the same binade, so the drift is exactly zero. This is why simulation codes often choose time steps like s.
6. Defend your work
Submit: main.py, the pytest -v log, drift_vs_steps.png with its CSV, and your tolerance note. Use the report template in projects/_template/report-template.md for the note.
Adversarial self-checks
- What if the lift force doubles? doubles, does not: the round-trip test must still pass, and
lift_to_dragmust change. Does your suite notice if someone accidentally squares the lift? - What if ?
dynamic_pressurereturns exactly 0.0 (no rounding: exactly) butlift_coefficientmust raise. Why is it right for the two functions to behave differently? - Which assumption fails first in the real world? The parabolic polar near stall. Which test would still pass with a stalled wing, and what new test would catch it?
- Does the result survive a change in solver or input? Replace
0.5 * rho * v ** 2byrho * v * v / 2: which tests pass, which fail, and is a failure here a bug? - Which decision changes if the uncertainty doubles? If your stored reference table had been rounded to 4 figures instead of 8, what tolerance would the regression test need, and could it still detect a 0.01 % change in ?
Check yourself
- In your own words, why is
0.1 + 0.2 == 0.3false, and what is the size of the difference compared with 0.3? - Which tolerance would you use to compare with a hand value, and why not
1e-3? is_close(0.0, 1e-15)isFalsewith the default tolerances. What single argument makes itTrue, and when is that the right thing to do?- A regression test fails after you corrected a genuine bug in
drag_polar. What do you do withREFERENCE_POLAR, and what do you write in the commit message? - State the limiting case of as and the physical meaning of that limit.
- Why does
lift_coefficientreject whiledynamic_pressureaccepts it? - For and , compute and by hand, then check with
max_lift_to_drag. - A colleague says "the parametrized test passes for four polars, so the formula is proven". What is wrong with that statement?
Problem set
Attempt every problem before opening solutions/. Record what you tried. State units and the tolerance you would accept on every numerical answer.
Several problems use your personal seed s: the day of the month you were born (1โ31). Write it at the top of your work.
1. (Warm-up: coefficients in level flight)
A light aircraft of mass kg flies level at m/s at sea level ( kg/mยณ, m/sยฒ), wing area mยฒ. In level flight lift equals weight.
Find: (a) the dynamic pressure in Pa; (b) ; (c) and from the default polar , ; (d) the drag force in N. Answer form: four numbers with units, each to four significant figures, and a one-line check of (b) with lift_coefficient.
2. (Derivation: two optima on the polar)
Starting from :
(a) Derive and by setting . Show that at the optimum the induced drag equals , so .
(b) The power required for level flight is proportional to . Derive the lift coefficient that minimises power and show it is times the lift coefficient of best .
(c) State one physical assumption used in (a) that is violated near stall, and say in one sentence what a test for would do if the real polar were used instead.
Answer form: derivation with each step named; two formulas; one short paragraph.
3. (Floating point by hand)
(a) Convert 0.1 to binary by repeated doubling until the pattern repeats. Write the repeating block.
(b) The spacing between neighbouring float64 values near a number is the ulp, . Compute the ulp near 1531.25 and near 0.3. Check both with math.ulp.
(c) 0.5 * 1.225 * 50.0 ** 2 involves two roundings (1.225 is not exact; the product is rounded). Give an upper bound, in ulps and in pascals, on how far the result can be from 1531.25. Then evaluate it in Python and report the actual difference.
(d) Using (c), justify the rel=1e-12 in test_dynamic_pressure_analytic_value. Could it be rel=1e-15? Answer form: short calculations and two sentences.
4. (Unfamiliar scenario: a wind-tunnel balance in imperial units)
A colleague hands you coefficient_from_balance(force_lbf, q_psf, area_ft2), which should return a dimensionless coefficient from a wind-tunnel balance that logs force in pounds-force and dynamic pressure in pounds-force per square foot. You have not seen the code.
Write, in prose or as Python, three tests: one against a known case you can compute by hand, one limiting case, and one invalid-input case. For each, state the tolerance and justify it with a number. Then say which single test would catch a stray factor of 32.174 (the lbm-to-lbf slug conversion) inside the function, and why the others might not.
5. (Numerical, uses your code: measure the drift)
Run the computational experiment of lesson part 4 with kg and a 10 kg total burn, for steps.
Report: the table (n, dt_s, drift_kg, bound_kg), the log-log plot, and the slope of against from a straight-line fit over the points where the drift is non-zero. Compare the slope with 1 (the worst-case bound) and 0.5 (random-walk cancellation). Then repeat with the step chosen as exactly 0.125 kg and explain the result. Answer form: table, plot, slope with its uncertainty, two paragraphs.
6. (Judgment: when the regression test fails)
You change K_DEFAULT from 0.050 to 0.045 because the aircraft got a new wing with higher aspect ratio. test_polar_table_matches_stored_reference fails; every other test passes.
(a) Is the code wrong, the test wrong, or neither? What exactly do you do with REFERENCE_POLAR, and what do you write in the commit message?
(b) Now suppose instead that you did not change anything deliberately, you only "cleaned up" drag_polar, and the same test fails with a relative difference of . List the two most likely causes and the one measurement that distinguishes them.
(c) A reference value for a later lesson will come from scipy.integrate.solve_ivp run with rtol=1e-8. What is the tightest tolerance you can honestly use in a regression test against it, and why is "tighter is always better" wrong here?
7. (Hard, uses your code: does the suite catch planted bugs?)
Mutation testing means deliberately breaking the code and checking that at least one test fails. Plant each of the following bugs in a copy of your main.py, one at a time, run the suite, and record which tests fail:
drag_polarreturnscd0 + k * cl(missing square).dynamic_pressurereturnsrho * v ** 2(missing one half).max_lift_to_dragreturns(math.sqrt(cd0 / k), 1.0 / math.sqrt(cd0 * k))(missing the 2)._check_positiveuses< 0.0instead of<= 0.0.is_closeusesmin(abs(a), abs(b))instead ofmax.
For any bug that no test catches, write a new test that does, with its tolerance justified. Answer form: a 5-row table of bug versus failing tests, plus any new test code.
Get the code
Clone the repository once, write your code in starter/main.py, then run the tests from the repository root.
pytest curriculum/phase-00/lesson-07-testing-engineering-code
To run the same tests against the reference solution instead:
AEFS_IMPL=solution pytest curriculum/phase-00/lesson-07-testing-engineering-code
Found a mistake? Every page is built from the Markdown in the repository; edit it on GitHub.