AThe project
Portfolio outcome: a small Python program that reads a quantity written the way an engineer writes it,
4.7 kohm 5%, converts it to SI base units, does arithmetic on it while tracking both the dimensions and the uncertainty, refuses to add a length to a time, and prints the answer to a defensible number of significant figures.
This is the first program in the course, and it assumes you have never written one. Everything it needs is taught below, in the order you use it, and nothing beyond that is used. No prior programming is required, and none is assumed later either: each project in this course introduces at most one or two new pieces of the language and teaches them where they are used. If you already program, read the two reference blocks and skip the primer.
The lessons in this topic apply their rules by hand. This project makes four of those rules executable. Implementing a rule tests understanding more strictly than stating it, because the program rejects any step that is unclear.
The four rules, each from a lesson in this topic:
- A prefix is a power of ten, and the SI base unit of mass is the kilogram, so a milligram is kg.
- A dimension is a list of exponents over the base units, and two quantities may be added only when those lists match.
- Relative uncertainties add on a product or quotient; absolute uncertainties add on a sum or difference.
- A result is reported to the significant figures its inputs support, with the uncertainty stated beside it.
The central idea of the project is the dimension vector. In this program a dimension is five numbers, not a label like "m/s", because labels cannot be multiplied. The five numbers are the exponents of the five base units this project uses:
A metre is . A second is . A speed, a metre divided by a second, is : the exponents subtract. Multiplying two quantities adds these five numbers position by position, dividing subtracts them, and two quantities can be added exactly when their five numbers are equal. With this representation, dimensional analysis becomes a mechanical check that the program applies to every operation.
Enough Python to build this.
Python runs a file of instructions from top to bottom. Install it from python.org if you do not have it, put your instructions in a file ending in .py, and run it by opening a terminal in that folder and typing python main.py. On many systems the command is python3 instead, so try both and use whichever works.
# Anything after a # is a note to a human. Python ignores it.
speed = 25.0 # a NAME bound to a value. No declaration, no type.
label = "metres per second" # text is written in quotes and is called a string
print(speed, label) # print puts things on the screen
# A FUNCTION is a named piece of work. It takes inputs and hands back a result.
def area(width, height): # def, the name, the inputs, then a colon
return width * height # the indented lines are the body. Indentation IS the grouping.
print(area(3.0, 4.0)) # calling it: 12.0
# A default gives an input a value for callers who do not supply one.
def power(base, exponent=2): # power(5) means power(5, 2)
return base ** exponent # ** is "to the power of"
# IF chooses between paths. == asks whether two things are equal, != whether they differ.
if speed > 20.0:
print("fast")
else:
print("slow")
# A LIST is an ordered, changeable collection, written with square brackets.
readings = [12.1, 12.4, 12.2]
readings.append(12.3) # add one to the end
print(readings[0]) # counting starts at ZERO, so this is 12.1
print(len(readings)) # how many: 4
# A TUPLE is a list that cannot be changed, written with round brackets.
# The dimension vector is a tuple, because a metre must stay a metre.
metre = (1, 0, 0, 0, 0)
print(metre[2]) # 0
# A DICTIONARY maps a key to a value, written with curly brackets. The unit tables
# are dictionaries, and so is a quantity in this project.
prefixes = {"m": -3, "k": 3}
print(prefixes["k"]) # 3
print("k" in prefixes) # True: asking whether a key is present
q = {"value": 4700.0, "rel": 0.05}
q["value"] = 4700.0 # read and write with the same square brackets
# A FOR LOOP repeats the body once per item. range(5) counts 0, 1, 2, 3, 4.
total = 0
for i in range(5):
total = total + metre[i]
# STRINGS join with +, and str(x) turns a number into text so it can be joined.
print("speed is " + str(speed))
# A program that cannot go on RAISES an error, naming what went wrong.
def halve(x):
if x < 0:
raise ValueError("cannot halve a negative length")
return x / 2.0
# A caller who expects that can CATCH it instead of stopping.
try:
halve(-1.0)
except ValueError as err:
print("refused:", err)
# A program in several files: put each in the same folder and IMPORT by filename.
# import dimension then call dimension.multiply(a, b)
This is all the Python the project uses. It uses no classes, no regular expressions and no testing framework, and the checks at the end are ordinary if statements in a file that is run like any other.
Syntax you need here.
# the five forms this project is built from
result = [] # dimension arithmetic: one loop, no shortcuts
for i in range(5):
result.append(a[i] + b[i]) # swap + for - to divide
dim = tuple(result)
addable = (a == b) # two tuples compare position by position
raise ValueError("cannot add m and s") # the refusal, as a message a caller can read
parts = "4.7 kohm 5%".split() # ['4.7', 'kohm', '5%'] - split on spaces
number = float(parts[0]) # text to number
rest = parts[1:] # everything from position 1 onwards
is_percent = parts[2].endswith("%") # True
without_sign = parts[2][:-1] # '5', dropping the last character
float(format(x, ".2e")) # round to 3 SIGNIFICANT FIGURES, not decimals
- Five numbers, position by position. The loop over
range(5)adds or subtracts two exponent vectors. Comparing two tuples with==already compares them position by position, so the addability test is one expression. - The refusal.
raise ValueError("...")with a message naming both dimensions. This project uses the built-inValueErrorfor every refusal; a larger program would define its own error type with theclasskeyword, which this project does not need. - Splitting text.
.split()cuts a string at its spaces into a list..endswith("%")tests the last character and[:-1]removes it, which is all the parsing this format needs. - Significant figures.
format(x, ".2e")writesxin scientific notation with two digits after the point, which is three significant figures, andfloat(...)reads that back as a number. So rounding to significant figures is scientific notation with decimals, which is the same statement the powers lesson made about where precision is carried. - Joining text.
str(x)then+, and".".join(parts)glues a list of strings with a dot between them.
Project layout. Every project in this course follows one rule: the policy imports no framework. The part that holds the engineering, here the dimensions and the uncertainty arithmetic, must be usable without any parsing or printing, so parsing sits on one side of it and reporting on the other, and main.py only connects them.
unitcalc/
|-- tables.py # THE TABLES: prefixes, units, output precision. No logic.
|-- dimension.py # THE DIMENSION VECTOR: multiply, divide, name. Knows nothing about values.
|-- quantity.py # THE POLICY: value + dimension + uncertainty, and the arithmetic rules.
|-- parsing.py # THE INPUT BOUNDARY: "4.7 kohm 5%" -> a quantity.
|-- report.py # THE OUTPUT BOUNDARY: significant figures, unit conversion, printing.
|-- main.py # wires them and runs the worked examples from the lessons.
`-- checks.py # the proofs: one check per rule, run with python checks.py
With this split, quantity.py can be exercised with hand-built dictionaries and never sees a string, so a failing uncertainty check points to the arithmetic and nothing else. A later change to the text format touches parsing.py alone.
The other pieces come from earlier lessons:
| Piece | Lesson | Call |
|---|---|---|
| prefixes as powers of ten | Powers, roots and scientific notation | 10 ** PREFIXES[prefix] |
| the kilogram trap | Units, SI prefixes and dimensional analysis | "g": ((0,1,0,0,0), 1e-3) |
| dimensions as exponent vectors | Units, SI prefixes and dimensional analysis | result.append(a[i] + b[i]) |
| refusing a bad addition | Units, SI prefixes and dimensional analysis | raise ValueError(...) |
| relative uncertainty on a quotient | Significant figures, rounding, tolerance and error | a["rel"] + b["rel"] |
| absolute uncertainty on a sum | Significant figures, rounding, tolerance and error | absolute(a) + absolute(b) |
| percentage to a fraction | Fractions, decimals and percentages as one idea | float(part[:-1]) / 100.0 |
| significant figures | Significant figures, rounding, tolerance and error | float(format(x, ".2e")) |
| conversion by cancellation | Ratios, proportion and scaling | q["value"] / (factor * 10 ** PREFIXES[prefix]) |
Make a folder called unitcalc. Inside it create main.py containing two lines: def main(): print("unitcalc") and, underneath and not indented, if __name__ == "__main__": main(). The second line is the standard way for a Python file to say "when this file is the one being run, start here". It appears in almost every Python program, and it lets main.py be imported later without running anything. Do this before writing any of the calculator, so that a failure at this point is a failure of the Python installation, not of the code.
Check: python main.py from inside unitcalc prints unitcalc and returns to the prompt. If the command is not found, try python3 main.py; if that works, use python3 everywhere below.
Write PREFIXES as a dictionary from symbol to exponent, not to a multiplier: {"p": -12, "n": -9, "u": -6, "m": -3, "": 0, "k": 3, "M": 6, "G": 9}. Storing the exponent rather than 1e-6 keeps the table readable and makes the powers lesson's arithmetic visible at the point of use. The entry for the empty string is what lets a unit with no prefix take the same code path as one with a prefix, so nothing downstream needs a special case. Write UNITS as a dictionary from symbol to a pair, the dimension tuple and the factor that converts one of this unit into SI base units. Include m, g, s, A, K, N, J, W, V, ohm, F, Hz, min, h, L. Set SIG_FIGS = 3, the number of significant figures every printed result uses unless a caller asks for another. Two entries need care. Give g the factor 1e-3, because the SI base unit of mass is the kilogram. This one entry makes kg come out as 1.0 and mg as without any special case elsewhere. Give min the factor 60.0 and h the factor 3600.0, so a conversion never needs a remembered direction.
Check: python -c "import tables; print(tables.UNITS['g'], tables.PREFIXES['k'])" prints the pair and 3. Confirm by hand that 1e-3 * 10**3 is 1.0, which is a kilogram.
Define BASE = ("m", "kg", "s", "A", "K") and NONE = (0, 0, 0, 0, 0), the dimension of a pure number. Write three functions. multiply(a, b) builds an empty list, loops for i in range(5) appending a[i] + b[i], and returns tuple(result); a tuple is returned instead of the list because a dimension must not be editable after it is made. divide(a, b) is the same loop with a minus. name(d) loops over the five positions, skips any exponent that is zero, appends BASE[i] when the exponent is 1 and BASE[i] + "^" + str(d[i]) otherwise, and finally returns ".".join(parts), or "1" when the list is empty, since a dimensionless quantity is a pure number. This module holds no values and imports nothing, which is why it can be checked in one line.
Check: multiply((1,0,0,0,0), (0,0,-1,0,0)) returns (1, 0, -1, 0, 0) and name of that is m.s^-1. name(NONE) returns "1".
A quantity is a dictionary with exactly three keys: "value", a number always in SI base units; "dim", the tuple; and "rel", the relative uncertainty as a fraction, so 5% is 0.05. Write make(value, dim, rel=0.0) returning that dictionary, converting the value and the uncertainty with float() and the dimension with tuple() so that a caller passing an integer or a list cannot produce two shapes of the same thing. The default of 0.0 means a quantity with no stated tolerance is treated as exact, which is the right reading of 5 V written with no percentage. Write absolute(q) returning abs(q["value"]) * q["rel"], the uncertainty as a quantity rather than a fraction. Then write multiply(a, b) and divide(a, b): the values multiply or divide, the dimensions go through dimension.multiply or dimension.divide, and the relative uncertainties add in both cases. Adding them is the worst-case rule from the precision lesson. Turn 2 replaces it with the statistical rule, and the simple version keeps the last check readable. A dictionary instead of a custom type gives up a custom print format, and in return the program needs no classes, and printing a quantity shows exactly what it contains.
Check: build make(5.0, (2,1,-3,-1,0), 0.01) and make(4700.0, (2,1,-3,-2,0), 0.05) by hand and divide them. The value is about 1.064e-3, the dimension is (0, 0, 0, 1, 0), which name reports as A, and rel is 0.06.
Write one helper, combine(a, b, value, verb), and then add and subtract as one line each that call it with a["value"] + b["value"] or a["value"] - b["value"] and the word "add" or "subtract". Both operations share the dimension check and the uncertainty arithmetic, and only the value and the word in the message differ, so writing them twice would duplicate the rule. combine must first compare a["dim"] with b["dim"] and raise ValueError naming both dimensions when they differ, because this refusal is the reason for carrying dimensions at all. When they match, add the two absolute uncertainties and convert the total back into a relative one by dividing by the new value. Guard the case where that value is exactly zero, since dividing by it would fail. Return a relative uncertainty of 0.0 there, and note that this is a limitation, not a fix, for the reason discussed in section C.
Check: adding two make(100.0, (1,0,0,0,0), 0.01) gives a value of 200.0 and an absolute of 2.0, so rel stays 0.01. Subtracting make(834.9, (0,1,0,0,0), 0.0006) from make(847.2, (0,1,0,0,0), 0.0006) gives about 12.3 with a rel near 0.082, which is the catastrophic cancellation from the precision lesson appearing as a number.
Write split_symbol(symbol) first: if the symbol is itself a key in UNITS, return ("", symbol), and only otherwise loop over the prefixes, skipping the empty one, and return the prefix and the remainder as soon as symbol.startswith(prefix) and the remainder is a known unit. Raise ValueError naming the symbol if nothing matches. The whole symbol must be checked first: m is both a prefix and the metre, and min starts with the prefix m, so a parser that tries prefixes first would read a minute as a milli-something. Then write parse(text): split() the text, read float(parts[0]) as the value, and loop over parts[1:] treating any part ending in % as the tolerance, converted with / 100.0, and any other part as the unit symbol. Look up the dimension and factor, and return quantity.make(value * factor * 10 ** PREFIXES[prefix], dim, rel). A quantity written with no unit at all is dimensionless, so return NONE as its dimension rather than guessing. Raise ValueError on anything you cannot read rather than guessing.
Check: parse("4.7 kohm 5%") has a value of 4700.0 and a rel of 0.05. parse("1 kg")["value"] is 1.0 and parse("1 mg")["value"] is 1e-6. parse("1 min")["value"] is 60.0, which proves the whole-symbol check works, and deleting that check makes this one line fail while every other check still passes.
Write round_sig(x, figures) returning 0.0 when x is zero and otherwise float(format(x, "." + str(figures - 1) + "e")), which is the scientific-notation identity from the reference block: significant figures is decimals in scientific notation. Write in_unit(q, symbol), which splits the symbol the same way the parser does, looks up the dimension and factor, raises ValueError when the dimension does not match, and otherwise returns q["value"] / (factor * 10 ** PREFIXES[prefix]). That division is conversion by cancellation, made executable. Write describe(q, unit=None, figures=SIG_FIGS): unit=None means report in base units and label with dimension.name, since that is the only label available when no unit was asked for, and figures=SIG_FIGS takes the default from the table so the precision of the whole program is one line in one file. Return the value rounded to figures, the label, and, when rel is not zero, the absolute band rounded to two significant figures and the percentage, also to two. An uncertainty is never known to three figures, so the band is stated to two.
Check: in_unit(parse("4.7 kohm"), "ohm") is 4700.0 and in_unit(parse("4.7 kohm"), "kohm") is 4.7. in_unit(parse("1 m"), "s") raises ValueError. describe(parse("5.00 V 1%")) reads 5.0 +/- 0.05 m^2.kg.s^-3.A^-1 (1.0%).
Replace the one-line main() you wrote in step 1. Import parsing, quantity and report, and print four results and nothing else. The current through the resistor, parse("5.00 V 1%") divided by parse("4.7 kohm 5%"), reported in mA. The speed, parse("90 km") divided by parse("1 h"), which should come out at 25 in base units. The hydraulic power of the pump from the units lesson: build the volume flow from 45 L over 1 min, build the density as make(1000.0, (-3, 1, 0, 0, 0)) because the tables carry no unit symbol for it, multiply to get the mass flow, then multiply by make(9.81, (1, 0, -2, 0, 0)) for gravity and by parse("12 m") for the height. Building those two by hand shows that the tables are a convenience and that the dimension vector carries the meaning. And a deliberate failure: add a metre to a second inside a try and print the ValueError message, so the program demonstrates the refusal rather than only claiming it.
Check: python main.py prints the current as 1.06 +/- 0.064 mA (6.0%), the speed as 25.0 m.s^-1, the pump power as 88.3 W, and a line reading refused: cannot add m and s. Every one of those numbers appears in a lesson in this topic, so you can check them without running anything.
Write TOLERANCE = 1e-9 and an empty list FAILURES at the top, then check(label, got, want), which prints ok and the label when abs(got - want) is within TOLERANCE times max(1.0, abs(want)) and otherwise prints FAIL, the label and both numbers and appends the label to FAILURES. A tolerance is needed instead of == because 0.1 + 0.2 is not 0.3 in binary floating point, as the fixed-point and floating-point lesson in Turn 2 explains, and scaling the tolerance by the size of the expected value is what makes one constant work for both 1e-6 and 4700. Write check_refuses(label, function, first, second), which calls function(first, second) inside a try, prints ok if a ValueError arrives and records a failure if none does. Then write one check per rule and no more: that prefixes reach SI base units, including 1 kg as 1.0, 1 mg as 1e-6 and 1 min as 60.0; that relative uncertainties add on a quotient, using the resistor case; that absolute uncertainties add on a sum, using two 100 m lengths at 1% giving a band of 2.0; that a mismatched addition and a mismatched in_unit both refuse. Add one more check: that subtracting two nearly equal masses inflates the relative uncertainty by more than a hundredfold, which is catastrophic cancellation asserted as a property rather than described in prose. Build that last one's inputs with make directly rather than with parse, because it is a check on the arithmetic and must not fail when someone edits the unit table. End by printing all checks passed when FAILURES is empty and the count otherwise.
Check: python checks.py prints a line per check and then all checks passed. Then break one thing on purpose, change the g factor in tables.py to 1.0, and confirm that only the two checks about grams fail, the kilogram and the milligram, while every other check still passes. The one to watch is the cancellation check: it builds its inputs with make rather than with parse, so an edit to the unit table cannot reach it. A check that an unrelated table edit can break will eventually report a fault in the wrong module.
Full solutiontry the steps first - click to reveal
The complete calculator, one file at a time, in build order. Read it after your own version refuses to add a metre to a second, since the refusal is the part that tests understanding of the dimension vector.
# tables.py - the tables the calculator is configured by. No logic lives here.
# Prefix symbol -> power of ten. Stored as the EXPONENT, not the multiplier, so the
# powers lesson's arithmetic stays visible at the point of use. The empty-string entry
# lets an unprefixed unit take the same path as a prefixed one.
PREFIXES = {"p": -12, "n": -9, "u": -6, "m": -3, "": 0, "k": 3, "M": 6, "G": 9}
# Unit symbol -> (dimension over (m, kg, s, A, K), factor into SI base units).
# NOTE the gram: the SI base unit of mass is the KILOGRAM, so one gram is 1e-3 of it.
# That single line is what makes "kg" come out as 1.0 and "mg" as 1e-6, with no
# special case anywhere else in the program.
UNITS = {
"m": ((1, 0, 0, 0, 0), 1.0),
"g": ((0, 1, 0, 0, 0), 1e-3),
"s": ((0, 0, 1, 0, 0), 1.0),
"A": ((0, 0, 0, 1, 0), 1.0),
"K": ((0, 0, 0, 0, 1), 1.0),
"N": ((1, 1, -2, 0, 0), 1.0),
"J": ((2, 1, -2, 0, 0), 1.0),
"W": ((2, 1, -3, 0, 0), 1.0),
"V": ((2, 1, -3, -1, 0), 1.0),
"ohm": ((2, 1, -3, -2, 0), 1.0),
"F": ((-2, -1, 4, 2, 0), 1.0),
"Hz": ((0, 0, -1, 0, 0), 1.0),
"min": ((0, 0, 1, 0, 0), 60.0),
"h": ((0, 0, 1, 0, 0), 3600.0),
"L": ((3, 0, 0, 0, 0), 1e-3),
}
# How many significant figures a printed result carries unless a caller asks otherwise.
SIG_FIGS = 3
# dimension.py - a dimension is five exponents over the SI base units.
# This module holds no values and imports nothing, which is why it is trivial to check.
BASE = ("m", "kg", "s", "A", "K")
NONE = (0, 0, 0, 0, 0) # the dimension of a pure number
def multiply(a, b):
"""Dimensions of a product: exponents add, position by position."""
result = []
for i in range(5):
result.append(a[i] + b[i])
return tuple(result)
def divide(a, b):
"""Dimensions of a quotient: exponents subtract."""
result = []
for i in range(5):
result.append(a[i] - b[i])
return tuple(result)
def name(d):
"""A readable spelling, e.g. (1, 0, -1, 0, 0) -> 'm.s^-1'."""
parts = []
for i in range(5):
if d[i] == 0:
continue
if d[i] == 1:
parts.append(BASE[i])
else:
parts.append(BASE[i] + "^" + str(d[i]))
if len(parts) == 0:
return "1"
return ".".join(parts)
# quantity.py - THE POLICY. A measurement is a value in SI base units, a dimension,
# and a relative uncertainty. This file imports no parser and no formatter, so a
# failing check here blames the arithmetic and nothing else.
import dimension
def make(value, dim, rel=0.0):
"""Build a quantity. rel is a FRACTION, so 5% arrives as 0.05.
The default of 0.0 reads a value with no stated tolerance as exact.
"""
return {"value": float(value), "dim": tuple(dim), "rel": float(rel)}
def absolute(q):
"""The uncertainty as a quantity rather than as a fraction."""
return abs(q["value"]) * q["rel"]
def multiply(a, b):
"""Product: values multiply, dimensions add, RELATIVE uncertainties add."""
return make(a["value"] * b["value"],
dimension.multiply(a["dim"], b["dim"]),
a["rel"] + b["rel"])
def divide(a, b):
"""Quotient: values divide, dimensions subtract, RELATIVE uncertainties add."""
return make(a["value"] / b["value"],
dimension.divide(a["dim"], b["dim"]),
a["rel"] + b["rel"])
def combine(a, b, value, verb):
"""The shared half of add and subtract: the refusal, and ABSOLUTE uncertainties.
Written once because the dimension check and the uncertainty arithmetic are the
same for both, and only the value and the word in the message differ.
"""
if a["dim"] != b["dim"]:
raise ValueError("cannot " + verb + " " + dimension.name(a["dim"])
+ " and " + dimension.name(b["dim"]))
band = absolute(a) + absolute(b)
if value == 0.0:
# Relative uncertainty is undefined at zero. Reporting 0.0 here claims perfect
# confidence in the number this arithmetic knows least about: a real limitation
# of storing the uncertainty as a fraction, not a fix.
return make(0.0, a["dim"], 0.0)
return make(value, a["dim"], band / abs(value))
def add(a, b):
return combine(a, b, a["value"] + b["value"], "add")
def subtract(a, b):
return combine(a, b, a["value"] - b["value"], "subtract")
# parsing.py - THE INPUT BOUNDARY. Engineer's text in, a quantity out.
import dimension
import quantity
import tables
def split_symbol(symbol):
"""'kohm' -> ('k', 'ohm'). Checks the WHOLE symbol before trying any prefix,
because 'm' is both milli and the metre, and 'min' begins with 'm'."""
if symbol in tables.UNITS:
return ("", symbol)
for prefix in tables.PREFIXES:
if prefix == "":
continue
if symbol.startswith(prefix):
rest = symbol[len(prefix):]
if rest in tables.UNITS:
return (prefix, rest)
raise ValueError("unknown unit: " + symbol)
def parse(text):
"""'4.7 kohm 5%' -> a quantity of 4700 ohms with a relative uncertainty of 0.05."""
parts = text.split()
if len(parts) == 0:
raise ValueError("nothing to parse: " + repr(text))
value = float(parts[0])
symbol = ""
rel = 0.0
for part in parts[1:]:
if part.endswith("%"):
rel = float(part[:-1]) / 100.0
else:
symbol = part
if symbol == "":
return quantity.make(value, dimension.NONE, rel)
prefix, unit = split_symbol(symbol)
dim, factor = tables.UNITS[unit]
return quantity.make(value * factor * 10 ** tables.PREFIXES[prefix], dim, rel)
# report.py - THE OUTPUT BOUNDARY. Significant figures, conversion out of base
# units, and the printed line. No engineering rule lives here.
import dimension
import parsing
import tables
def round_sig(x, figures):
"""Round to a count of SIGNIFICANT FIGURES, not decimal places.
n significant figures is n-1 decimals in scientific notation, so writing the
number that way and reading it back IS the rounding.
"""
if x == 0.0:
return 0.0
return float(format(x, "." + str(figures - 1) + "e"))
def in_unit(q, symbol):
"""The value expressed in the named unit. Refuses when the dimension disagrees."""
prefix, unit = parsing.split_symbol(symbol)
dim, factor = tables.UNITS[unit]
if dim != q["dim"]:
raise ValueError("cannot express " + dimension.name(q["dim"]) + " as " + symbol)
return q["value"] / (factor * 10 ** tables.PREFIXES[prefix])
def describe(q, unit=None, figures=tables.SIG_FIGS):
"""A printable line. unit=None reports in base units, labelled by dimension."""
if unit is None:
value = q["value"]
label = dimension.name(q["dim"])
else:
value = in_unit(q, unit)
label = unit
shown = str(round_sig(value, figures))
if q["rel"] == 0.0:
return shown + " " + label
# Two figures on a band, never three: an uncertainty is not known to three.
band = str(round_sig(abs(value) * q["rel"], 2))
percent = str(round_sig(q["rel"] * 100.0, 2))
return shown + " +/- " + band + " " + label + " (" + percent + "%)"
# main.py - wires the five modules together and reproduces the lessons' examples.
import parsing
import quantity
import report
def main():
# 5.00 V across 4.7 kohm, both with a tolerance. Reported in milliamps.
current = quantity.divide(parsing.parse("5.00 V 1%"), parsing.parse("4.7 kohm 5%"))
print("current:", report.describe(current, unit="mA"))
# 90 km in 1 h, in base units, which is where the cancellation is visible.
speed = quantity.divide(parsing.parse("90 km"), parsing.parse("1 h"))
print("speed: ", report.describe(speed))
# The pump from the units lesson: 45 L/min lifted 12 m.
# Density and gravity are hand-built, because the tables carry no symbol for
# either, which is the point: the tables are a convenience, the vector is the thing.
volume_flow = quantity.divide(parsing.parse("45 L"), parsing.parse("1 min"))
density = quantity.make(1000.0, (-3, 1, 0, 0, 0))
gravity = quantity.make(9.81, (1, 0, -2, 0, 0))
mass_flow = quantity.multiply(volume_flow, density)
power = quantity.multiply(quantity.multiply(mass_flow, gravity),
parsing.parse("12 m"))
print("pump: ", report.describe(power, unit="W"))
# The refusal, demonstrated rather than claimed.
try:
quantity.add(parsing.parse("1 m"), parsing.parse("1 s"))
except ValueError as err:
print("refused:", err)
if __name__ == "__main__":
main()
# checks.py - one check per rule. Run with: python checks.py
import quantity
import parsing
import report
TOLERANCE = 1e-9 # floats are not exact; compare within a relative band
FAILURES = []
def check(label, got, want):
if abs(got - want) <= TOLERANCE * max(1.0, abs(want)):
print("ok " + label)
else:
print("FAIL " + label + ": got " + str(got) + ", wanted " + str(want))
FAILURES.append(label)
def check_refuses(label, function, first, second):
try:
function(first, second)
except ValueError:
print("ok " + label)
return
print("FAIL " + label + ": no refusal")
FAILURES.append(label)
# 1. Prefixes and units reach SI base units, kilogram trap included.
check("1 kg is one base unit of mass", parsing.parse("1 kg")["value"], 1.0)
check("1 mg is 1e-6 kg", parsing.parse("1 mg")["value"], 1e-6)
check("1 min is 60 s", parsing.parse("1 min")["value"], 60.0)
# 2. Relative uncertainties add on a quotient.
current = quantity.divide(parsing.parse("5.00 V 1%"), parsing.parse("4.7 kohm 5%"))
check("1% over 5% gives 6%", current["rel"], 0.06)
# 3. Absolute uncertainties add on a sum.
length = quantity.add(quantity.make(100.0, (1, 0, 0, 0, 0), 0.01),
quantity.make(100.0, (1, 0, 0, 0, 0), 0.01))
check("two 1% lengths give a band of 2 m", quantity.absolute(length), 2.0)
# 4. A dimension mismatch is refused at both boundaries.
check_refuses("adding m to s is refused", quantity.add,
parsing.parse("1 m"), parsing.parse("1 s"))
check_refuses("reporting m as s is refused", report.in_unit,
parsing.parse("1 m"), "s")
# 5. Catastrophic cancellation, asserted as a property of the arithmetic.
# Built with make, NOT with parse, so an edit to the unit table cannot break it.
heavy = quantity.make(847.2, (0, 1, 0, 0, 0), 0.0006)
light = quantity.make(834.9, (0, 1, 0, 0, 0), 0.0006)
difference = quantity.subtract(heavy, light)
if difference["rel"] > 100.0 * 0.0006:
print("ok subtracting near-equal masses inflates the uncertainty 100-fold")
else:
print("FAIL cancellation did not inflate the uncertainty")
FAILURES.append("cancellation")
if len(FAILURES) == 0:
print("all checks passed")
else:
print(str(len(FAILURES)) + " check(s) failed")
BImmediate Active Recall
QUERYWhy is a dimension represented as five numbers rather than a label like "m/s"?
REVEAL
Labels cannot be multiplied. A tuple of exponents over the base units lets a product add the five numbers position by position, a quotient subtract them, and an addition compare them with ==. With that representation, dimensional analysis becomes a mechanical check on every operation.
QUERYOne table entry in tables.py handles the kilogram trap. Which, and how?
REVEAL
tables.py handles the kilogram trap. Which, and how?"g": ((0, 1, 0, 0, 0), 1e-3). Giving the gram the factor into the base unit means kg parses as and mg as , with no special case anywhere else in the program.
QUERYWhy must split_symbol check the whole symbol before trying any prefix?
REVEAL
split_symbol check the whole symbol before trying any prefix?m is both the prefix milli and the metre, and min begins with m. A parser that tries prefixes first would read a minute as a milli-something. Checking the whole symbol first resolves the ambiguity in favour of the real unit.
QUERYWhy is quantity.py forbidden to import the parser or the formatter?
REVEAL
quantity.py forbidden to import the parser or the formatter?So the policy is checkable on its own. Built from hand-made dictionaries, it never sees a string, so a failing uncertainty check blames the arithmetic and nothing else. It also means changing the text format later touches parsing.py alone.
QUERYWhat does in_unit actually compute, and which lesson is it?
REVEAL
in_unit actually compute, and which lesson is it?q["value"] / (factor * 10 ** PREFIXES[prefix]), after refusing when the dimensions disagree. That division is conversion by cancellation from the ratios and units lessons, made executable: the refusal is the homogeneity check and the division is the conversion factor.
QUERYWhat does the check on two nearly equal masses assert, and why is it a check rather than a comment?
REVEAL
That subtracting 834.9 kg from 847.2 kg, each good to 0.06%, yields about 12.3 kg good to only about 8.2%, more than a hundredfold worse. It is a check because catastrophic cancellation is a property of the arithmetic, so it can be asserted and will fail if someone "simplifies" the uncertainty rules.
CConceptual Questions
Answer in your own words first, then compare with the model answer.
The calculator stores everything in SI base units internally and converts only at the boundaries. What does that gain, and what does it cost?
REVEAL MODEL ANSWER
The gain is a single representation for the arithmetic, which removes one class of bug entirely. If quantities kept the units they arrived in, every operation would have to decide whether to convert first, and a missed conversion would produce a plausible number, the failure the units lesson describes. With base units stored, addition compares dimensions only, never unit symbols, and 4700 ohm and 4.7 kohm are already identical by the time the policy sees them. The dimension tuple is the only thing carried alongside the value, which keeps quantity.py small. The cost is that the original spelling is lost. The program cannot echo a value in the unit the user typed unless that unit is passed to describe again, so a display layer has to make a choice that the input already contained. Converting in and out also introduces rounding in principle, though at double precision it is far below the uncertainties being tracked. This is the usual trade for a canonical internal form: uniformity in the core, at the price of some information at the edge. It suits this program because the core is where mistakes are expensive.
The code adds relative uncertainties on a product, which is the worst case rather than the statistically likely one. Defend that choice for this project, and say what would have to change to do better.
REVEAL MODEL ANSWER
Adding them assumes the two errors conspire, both landing at their extremes in the same direction, which for independent errors is unlikely. The statistically correct combination for independent relative errors adds them in quadrature, the square root of the sum of squares, which for 5% and 1% gives 5.1% rather than 6%. So the worst case overstates the band. It is still the right choice here for three reasons. It is correct as a bound, so a design that passes under this rule passes under the real one. It requires no assumption about independence, which this program has no way to check and which is often false, since two resistors from the same reel share a manufacturing error and are not independent at all. And it keeps the rule identical in form to the absolute rule used for sums, so the lesson being taught stays visible in the code. To do better, the program would need to know whether its inputs are independent, which means tracking the identity of each source of error rather than only its size, and combining in quadrature only across distinct sources. That is what the uncertainty lesson in Turn 2 introduces, and it is a change of data model, not of formula.
combine returns a relative uncertainty of 0.0 when the result is exactly zero, and the comment calls that a limitation rather than a fix. Explain the problem and how you would change the design to remove it.
REVEAL MODEL ANSWER
Relative uncertainty is undefined at zero, since it is a fraction of the value and the value is nothing. Subtracting two equal quantities produces a result of zero that is not certain at all: each input carried a band, and the difference lies somewhere within the sum of those bands. Returning 0.0 reports perfect confidence in the number the arithmetic knows least about, so the error points in the worst possible direction. The code does it because a quantity stores its uncertainty as a fraction, and a fraction of a zero value cannot hold an absolute band. The fix is a change of representation, not a special case: store the absolute uncertainty under the key and compute the relative one on demand in a function. The sum rule then becomes a plain addition of stored values with no division, zero results carry their band correctly, and the product rule converts to relative, adds, and converts back. The change is more expressive and barely longer, which suggests the original choice of key was the weaker one, and the difference shows only in this edge case because elsewhere the two representations are interchangeable.
DPractice Problems
P1 (easy). Using the calculator, evaluate quantity.multiply(parse("22 kohm"), parse("100 nF")) and report the result with describe. What dimension comes out, and what does that confirm about the RC time constant?
P2 (medium). Add a unit to tables.py that the tables do not yet have: the bar, where 1 bar is Pa and a pascal is a newton per square metre. (a) What dimension tuple does it need? (b) Verify with the hydraulic cylinder from the units lesson that multiplying parse("160 bar") by parse("3.117e-3 m") and then by parse("1 m") gives about 49 880 N. (c) Explain why the two length terms are needed and what would happen if you wrote parse("3.117e-3 m") alone.
P3 (harder). The describe function rounds the value to SIG_FIGS significant figures regardless of the uncertainty it carries. (a) Explain why that is wrong, using 1.0638 mA +/- 6% as the example. (b) Write down the rule that should replace it, in words. (c) Sketch the change to describe, and say which existing check would have to be rewritten.
Solutionsclick to reveal
P1. parse("22 kohm") is 22000 with dimension , and parse("100 nF") is with dimension . Multiplying adds the exponent tuples element by element, giving , which name reports as s. The value is , so describe prints 0.0022 s. The dimension coming out as pure seconds confirms that an ohm times a farad is a time, which is the check from the units lesson performed by the program rather than by hand. Had you written quantity.divide instead of quantity.multiply, the dimension would have been , which is not a time by any reading, and the mistake would be visible without knowing anything about circuits.
P2. (a) A pascal is a newton per square metre, so its dimension is that of the newton, , divided by , giving . The entry is "bar": ((-1, 1, -2, 0, 0), 1e5). (b) parse("160 bar") is with that dimension. Multiplying by two lengths adds twice, giving , which is the newton. The value is , agreeing with the lesson's 49 880 to within the rounding of the area. (c) Two length terms are needed because pressure is force per area, so recovering a force requires multiplying by an area, and the calculator has no area unit, so an area is expressed as two lengths multiplied. Writing only one length would leave the dimension at , which is a force per metre rather than a force, and describe would print that dimension rather than N, catching the error immediately.
P3. (a) It is wrong because the precision of a result is set by its uncertainty, not by a constant. 1.0638 mA with a 6% band has an uncertainty of about 0.064 mA, which lands in the second significant figure, so the third figure is already meaningless and printing 1.06 implies a precision the value does not have. Three figures happens to be defensible here and would not be for a 30% band, where even the second figure is doubtful. (b) The rule: round the uncertainty to one significant figure, and then round the value to the same decimal place as the rounded uncertainty. By that rule the band becomes 0.06 mA and the value becomes 1.06 mA, which agrees here; for a 30% band the band is 0.3 and the value would be 1.1. (c) In describe, compute the band first and round it to one significant figure with round_sig(band, 1). Then find the decimal place that band occupies: write it in scientific notation with format(band, ".0e"), read the exponent off the text after the e, and round the value to that many places with Python's own round(value, -exponent). The figures argument then applies only to quantities with no uncertainty, where there is nothing else to go on. round_sig itself need not change, so none of the numeric checks move; what would have to be rewritten is any check asserting the exact string describe returns, which is a good argument for checking the numbers rather than the formatted line.
EFeynman Exercise
Explain to a competent programmer who has never thought about units: why a quantity needs three fields rather than one, why the dimension has to be a tuple of numbers rather than a label, and what a program of this shape prevents that a careful human cannot. Write your explanation, then compare.
REVEAL MODEL ANSWER
A measurement holds three pieces of information. The first is the number. The second is the kind of quantity it measures, because 5 volts and 5 metres cannot be compared and no arithmetic will make them comparable. The third is how well it is known, because 5.00 volts from a laboratory reference and 5 volts from a guess are different claims that look identical once written down. A quantity therefore carries three fields: value, dimension and uncertainty. The dimension has to be numeric, not a label, because arithmetic is done on it. If it were the string "m/s", multiplying two quantities would mean concatenating and simplifying strings, which needs a parser and many special cases. As five numbers, the powers of the metre, kilogram, second, ampere and kelvin, multiplication becomes adding those numbers pairwise, division becomes subtracting them, and the question "may these two be added?" becomes "are these two tuples equal?". Dimensional analysis reduces to a comparison of tuples. The program provides what a careful person cannot: consistency under fatigue and under change. A careful engineer checks the units on the line being written. The program checks every line, every time, including lines written months ago by someone else and the line where a units table is edited and a conversion changes meaning. It cannot detect a wrong formula, because a wrong formula with consistent units passes. It removes the errors in which the formula was right and the assembly was wrong, and those are the most frequent errors in practice.
FError Analysis Framework
The mistake: building the parser before the policy, so the dimension arithmetic is only ever exercised through text, and letting the uncertainty rules live in whichever module happens to need them.
Why it happens: parsing is the visible part. A program that reads 4.7 kohm and prints something looks like progress, while a module of tuple arithmetic looks like scaffolding, so work tends to start at the edge and move inward. The uncertainty rules then end up wherever the first caller needed them, usually inside the parser or the formatter, because that is where the first example was.
How to recognize it: a checks file where every check builds its input by parsing a string, so no check can distinguish a parsing bug from an arithmetic bug; an uncertainty calculation that appears in two places with slightly different rounding; a refusal that can only be triggered through the parser; a change to the text format that breaks checks about arithmetic.
How to correct it: build in dependency order, innermost first, which is the order the build steps use: tables, dimensions, policy, then the two boundaries. Check quantity.py with hand-built dictionaries so its checks never touch a string. Keep each rule in exactly one place, so the product rule lives in quantity.multiply and nowhere else. When a check fails, the layering shows which module to open before the error is read, which is the practical benefit of the split.
GMini Challenge
A colleague proposes extending the calculator to handle temperature, so that parse("20 degC") + parse("5 degC") works. Decide what the program should do, implement your decision in words, and say what it reveals about the difference between a unit and a scale.
REVEAL MODEL ANSWER
The program should refuse, and the refusal is the correct engineering answer. Celsius is not a unit in the sense the rest of the table uses: it is a scale with an offset, and 0 degC is 273.15 K, not zero kelvin. Every other entry in UNITS is a pure multiplication into the base unit, and the design depends on that, because a multiplicative factor commutes with the arithmetic. An offset does not. Adding 20 degC to 5 degC is meaningless as written: if both are absolute temperatures, the answer is not 25 of anything, since converting each to kelvin and adding gives 571.3 K, which is 298 degC and clearly not what was meant. One of the two quantities might be a temperature and the other a temperature difference, and a difference of 5 degC is exactly 5 K with no offset. The implementation follows from that distinction. Keep kelvin as the base unit, and add degC as a unit that may be parsed but carries an offset alongside its factor. Allow it in two operations only: converting a single quantity in or out, and subtracting two absolute temperatures to give a difference in kelvin. Refuse the addition of two absolute temperatures with a message naming the reason, and allow adding a kelvin difference to a Celsius absolute temperature, since that is well defined. The table's factor column encodes an assumption that was never written down: every unit is related to its base unit by a pure scaling. Celsius, Fahrenheit and gauge pressure break that assumption, and a design that admitted them without checks would produce wrong answers instead of errors, which is the worse failure.
Quiz Check
Answer without looking back.