TMP-SCI-204 · Planned course · Unfinished learning resource

Unit 3: Numerical representation, scale and error

TMP-SCI-204. This original teaching unit follows Units 1–2. It is not a new course, a supplied computing service, a qualification or an accredited programme. Use fictional values and an owned exercise folder. No instrument, private data, network connection, account, paid package or new installation is needed. EXECUTION CAPACITY UNRESOLVED remains: author execution is not learner access.

Start here

Unit 1 distinguished measured zero from missing data and kept the rate's units explicit. Unit 2 separated parsing, calculation and evidence writing. Now we ask a different question: How much of a computed answer comes from the intended numbers, and how much comes from the way those numbers were represented and calculated?

You need subtraction, fractions, ratios and elementary Python functions. A fraction a/b means a divided by b, with b nonzero. The absolute value |a| is the distance of a from zero. A power such as 2^3 means repeated multiplication, 2×2×2. Python writes that as 2**3; ^ is not Python exponentiation. Scientific notation 2e-9 means 2×10^-9, or 0.000000002. No calculus is assumed.

Proposed workload is 14 unpiloted hours: readiness/representation 2, cancellation and summation 3, tolerances/uncertainty 2, practice/audit 2, quiz 1, project 3, delayed transfer 1. This is not measured learner time or credit.

Outcomes: choose an appropriate numerical representation; distinguish exact input references from stored floats; calculate absolute/relative error; diagnose cancellation and order effects; justify a numerical comparison; distinguish arithmetic error from measurement bounds; preserve honest execution evidence.

R1. Reduce 125/1000 and 126/1000. What is 126/1000 minus 125/1000?

R2. A reported result is 0.004 and its reference is 0.005. Find the absolute difference and express it as a percentage of the reference.

R3. Two measured readings each have an absolute error no larger than 0.2 units. Why can their difference have an error as large as 0.4 units rather than 0.2?

R4. Your terminal is unavailable. Which can you honestly submit: a predicted output, a test design, a claim that tests passed, or an actual run record?

1. A number, its representation and its display are different things

An integer count such as 17 has no fractional part. A rational number is a ratio of integers. Some rationals have short decimal representations: 3/8 = 0.375. Others, such as 1/3, repeat indefinitely in base ten. Binary uses powers of two instead of powers of ten. Its fractional places have weights 1/2, 1/4, 1/8 and so on. Thus binary 0.011 means 0/2 + 1/4 + 1/8 = 3/8.

A reduced fraction has a finite binary expansion exactly when its denominator is a power of two. Why? A finite binary expansion can always be placed over a denominator 2^k. Conversely, a numerator divided by 2^k fits in k fractional places, provided the available format also has sufficient precision and range. Therefore 3/8 can be exact in the format used here, whereas 1/5 cannot have a finite binary expansion. This is a mathematical restriction, not evidence that the computer is broken.

In the checked Python environment, float uses radix 2 and 53 significant binary digits. A float stores one of a finite set of representable values. The spacing between nearby values grows as their magnitude grows. This is unlike a fixed-width ruler with equally spaced marks everywhere. We inspect runtime properties rather than claiming all imaginable Python implementations must match this environment.

Python integers can grow beyond a fixed machine-word width, subject to memory and implementation limits. But converting an integer to float can lose information. Let N = 2^53 = 9,007,199,254,740,992. Here N and N+2 are representable floats, but N+1 lies halfway between them and rounds to N under the checked rounding behavior. Integer subtraction (N+1)-N gives 1. Converting both operands to float first gives a difference of zero. The loss happens before subtraction.

Fraction('0.2') constructs the exact rational 1/5 from decimal text. Fraction(0.2) describes the already rounded binary float exactly; it is a different rational. Neither constructor can know whether the physical measurement was accurate. “Exact” here refers to mathematical representation of a specified input, not perfect knowledge of the world.

Formatting a number to three decimal places changes its display. It does not repair the stored value, reverse lost input information, or establish measurement accuracy. Preserve useful internal precision and apply a stated display rule at the reporting boundary.

G1. Decide which fractions have finite binary expansions: 7/16, 3/20, 9/12 and 1/10. Reduce first. Explain why this alone does not guarantee that an arbitrarily large finite expansion fits a particular float format.

G2. Predict (N+1)-N and float(N+1)-float(N). Then execute in an existing interpreter if available. Explain why subtracting N after conversion cannot recover the lost unit.

2. Define the error before describing it

Suppose a calculation returns approximation a and the intended exact mathematical reference is r. The absolute error is |a-r|, with the same units as the result. For nonzero r, relative error is |a-r|/|r|, a dimensionless ratio. Multiplying this ratio by 100 gives percent error. Relative error is undefined when r=0. Do not silently divide by zero or call the error zero just because its denominator is zero.

An example with manageable arithmetic: a=0.004, r=0.005. Absolute error is 0.001. Relative error is 0.001/0.005=1/5=20%. If both values were in metres, the absolute error is 0.001 m; the relative error has no unit. Express both in millimetres and the absolute error becomes 1 mm while the relative error remains 20%.

These definitions require a stated reference. An exact reference for a mathematical exercise is not automatically the true physical value. We can compare a float calculation with exact rational arithmetic on supplied decimal tokens; that isolates numerical disagreement under that chosen input model. Measurement, model and transcription errors remain separate questions.

3. Cancellation: small differences between large readings

Consider a fictional instrument storing two cumulative position readings in metres:

Treat the tokens as exact decimal values for this first numerical investigation. The common trillion-metre offset cancels algebraically, leaving 0.126-0.125 = 0.001 m. The huge offset is chosen to expose representation limits, not to describe a realistic instrument.

In the checked environment, converting the full tokens to floats and then subtracting gives 0.0009765625 m = 1/1024 m. The exact decimal reference is 1/1000 m. Therefore absolute error is 1/1000-1/1024 = 3/128000 m = 0.0000234375 m. Relative error is (3/128000)/(1/1000)=3/128=0.0234375, or 2.34375%.

The full readings have very small relative representation errors, but their difference is tiny compared with their magnitude. Those pre-existing errors can dominate the difference. This is the central danger of cancellation. It does not mean subtraction always adds a new rounding error: the subtraction of these stored values can itself be exact, yet still be a poor approximation to the intended decimal difference.

There are different possible repairs, and their timing matters. If the original decimal tokens survive, exact rational subtraction can obtain the exact token difference. If the acquisition format can preserve a known baseline separately, small residuals may be converted instead. But subtracting the baseline only after the original tokens have already been rounded to floats cannot restore discarded information. Repeating the same calculation or printing more digits also cannot do that.

G3. Derive the worked absolute and relative errors without copying the output. State whether the percentage describes numerical error against decimal tokens or measured physical uncertainty.

G4. Compare three workflows: (a) convert full readings then subtract; (b) subtract the exact common baseline from preserved decimal tokens, convert residuals, then subtract; (c) convert full readings, subtract the baseline from those floats, then subtract residuals. Which can avoid the original conversion loss, and what original evidence is needed?

4. Addition order and what a better summation algorithm can recover

Mathematical addition of exact real numbers is associative: grouping does not change its result. Finite floating-point operations can break that identity. Take the exact integers 2^54, 3 and -2^54. The exact sum is 3. A deliberately left-to-right float loop first rounds 2^54+3 to 2^54+4, then subtracts 2^54, leaving 4. Group the large opposites first and the result is 3.

Our loop is explicit: start total = 0.0, then execute total += value for each input in order. We do not use Python's built-in sum as a synonym for this loop, because its implementation can use a more accurate algorithm depending on the Python version and operand type. The experiment must specify the algorithm it actually tests.

math.fsum is a standard-library tool designed to improve floating-point summation by retaining intermediate information. It returns 3 for this example. That does not make every calculation exact. If the tokens N+1 and -N are first converted to floats, they become N and -N. Even fsum then returns zero: the missing unit never reached the summation algorithm. Better accumulation addresses some arithmetic losses, not incorrect inputs or all representation losses.

Decimal arithmetic is another option when the input model is decimal. Its precision and rounding context still matter, and division such as 1/3 still requires approximation at finite precision. Creating a decimal from a rounded float preserves that float's value, not the original decimal token. Choosing a representation means choosing which quantities and operations need to remain exact, and acknowledging the costs and limits.

G5. Predict both orders of the three-term sum and then test them. Contrast that result with the N+1, -N input-loss example. Explain why “use fsum” is not a complete diagnosis.

5. Tolerance is an explicit acceptance rule

Exact equality is appropriate for many discrete properties: record counts, intended integer identifiers, or exact rational answers. For approximate numerical comparisons, state what difference is acceptable and why. For finite a and b, this unit uses:

|a-b| <= max(abs_tol, rel_tol × max(|a|, |b|)).

The maximum selects the larger allowance. abs_tol has the same units as a and b. rel_tol is dimensionless. The comparison is symmetric in a and b. It is not identical to relative error against a fixed exact reference, whose denominator is |r|. Do not silently swap these definitions.

For a=1000, b=1001 and rel_tol=0.001, the relative allowance is 1.001, so a difference of 1 passes. For a=1 and b=2 with the same relative tolerance, the allowance is 0.002, so a difference of 1 fails. Near zero, relative tolerance alone is ineffective: comparing zero with 2×10^-9 and rel_tol=0.01 permits only 2×10^-11, which is too small. A justified abs_tol=3×10^-9 permits the difference.

Choose a rule before inspecting whether your implementation passes. A rule that accepts the observed wrong answer merely because you widened it is not a useful test. Keep numerical regression tolerance distinct from the uncertainty of an instrument and from a scientific threshold. A loose tolerance can accept two equally wrong implementations; agreement is evidence of agreement, not correctness.

The companion requires finite numbers, excludes booleans, and requires 0<=rel_tol<1 and abs_tol>=0. NaN and infinity are rejected rather than treated as scientific observations. A failed computation is not made valid by attaching a tolerance.

G6. Calculate the allowance and pass/fail outcome for the two scale examples and the near-zero example above. If a and b change from metres to millimetres, how must abs_tol and rel_tol change?

6. Numerical precision is not measurement certainty

Now change the model. Suppose each worked reading's physical value is within 0.0001 m of its recorded decimal token. These are supplied deterministic bounds, not probabilities or confidence intervals. The smallest possible difference uses the smallest later reading and largest earlier reading. The largest uses the opposite combination. The difference therefore lies in [0.0008, 0.0012] m, a nominal 0.001 m plus or minus 0.0002 m.

This interval is conservative under the stated separate bounds. It does not require independence or a probability distribution. It may be wider than necessary if additional error dependence is known. If a single identical unknown calibration offset is added to both readings, that common offset cancels. Do not assume such cancellation for two unrelated errors merely because the same instrument recorded them.

We have now described three distinct things: exact subtraction of recorded decimal tokens, numerical error of a float calculation, and bounds on the physical difference under stated measurement assumptions. More printed digits address none of the missing measurement knowledge. Better arithmetic can reduce numerical error while leaving physical uncertainty unchanged.

7. Run and preserve the numerical investigation

Use an existing Python 3 interpreter. The author checked Python 3.12.14 with radix 2 and 53 mantissa bits. Keep numerical_lab.py and test_numerical_lab.py together. In a terminal opened in this package folder, record python3 --version, then run:

python3 -B -m unittest discover -v
python3 -B numerical_lab.py my-numerical-run-001

Use your verified interpreter command consistently, such as py instead of python3 if appropriate. The destination must be new and its parent must exist. No output directory is silently reused. The run writes report.json, a snapshot numerical_lab.py, and a final run.json containing interpreter information, arguments and hashes. Inputs are fixed in the source, so this source snapshot preserves them. This is not a CSV parser replacement for Unit 2.

The decimal-token contract permits an optional sign, 1–18 ASCII integer digits without leading zeroes except the single zero, and an optional decimal point followed by 1–12 digits. Examples: 0.2, -17.125, +3. Exponents, whitespace, .5, 1., fractions written with /, NaN and infinity are not accepted. Token strings and token lists are bounded, with 1–1000 terms for summation. These are exercise constraints, not universal scientific-data rules.

The source computes exact references from strings and computes float errors using Fraction(calculated_float). That deliberately records the exact rational value of the binary result. Subtracting two rounded display strings would introduce another representation choice and could hide the error being investigated.

To reproduce from preserved code, run python3 -B my-numerical-run-001/numerical_lab.py my-numerical-run-002. Under the same checked conditions the two report files should match. The run metadata can differ because arguments differ. Inspect valid completion JSON and compare the hashes for the two known filenames. A matching hash checks bytes, not authenticity or scientific validity. Work in a trusted owned folder and do not edit source during execution. If a write fails, partial output may remain. Preserve it and choose a new directory for a justified retry; this is not an atomic transaction or an adversarial filesystem sandbox.

For an additional case, save a separate small script beside the module:

from numerical_lab import difference_case
print(difference_case('17.375', '17.125'))

Record predictions before execution and keep the script/output. If execution is unavailable, label the work traced. No predicted result earns actual-execution credit.

8. Independent practice and audit

I1. Compare Fraction('0.2') and Fraction(0.2). Explain which represents the intended exact decimal token and which represents the stored float. Is either proof of measurement accuracy?

I2. For exact readings 17.125 and 17.375, derive the difference and predict float error. Explain how this contrasts with the large-offset worked example.

I3. Approximation a=0.0002 is compared with reference r=0. Find absolute error, say what happens to relative error, and design a justified absolute-only comparison if the stated numerical budget is 0.0003 units.

I4. Convert the worked absolute error from metres to millimetres. Recalculate its relative error and explain what stays invariant.

I5. Construct two values each within 1 unit of a middle value but more than 1 unit apart. What does this say about chaining approximate-equality comparisons?

I6. Design a four-case test set that would detect input conversion loss, order-sensitive summation, zero-reference handling and nonfinite input. Give independent expectations and say what each test would fail to establish.

H1. “Both readings print to the same three decimals, so their stored values are equal.” Diagnose the inference.

H2. “Our result passes a 5% comparison, so the real instrument is accurate to 5%.” Identify the missing evidence and the two different meanings of error.

H3. “Subtracting close numbers is always inaccurate, and fsum makes all arithmetic exact.” Refute both universal claims using contrasting cases from this unit.

9. Changed-input quiz: 30 formative points

Each question is worth 6 points. New exact decimal tokens: earlier 1000000000000.125, later 1000000000000.128. The companion's checked float difference is 25/8192 m; derive everything else independently.

Q1. Find the exact decimal-reference difference, absolute error, relative error and percent error. Label units correctly.

Q2. For this one regression test, a design specification allows absolute numerical error at most 0.00004 m. Use an absolute-only comparison. Does the supplied float result pass? Explain why changing the allowance after seeing the result is not a correction.

Q3. Each recorded reading has a supplied absolute measurement bound of 0.0002 m. Derive the physical difference interval and say whether it establishes a difference strictly above 0.0032 m.

Q4. Explain how exact token subtraction, recentering before float conversion and recentering after conversion differ. Which can recover information from tokens that no longer exist?

Q5. Execute or explicitly trace the quiz case and a contrasting exact-binary case. Submit predictions, commands/source, results, one discriminating test and a limitation. Distinguish your evidence from the author's run.

10. Project: a defensible tiny displacement, 40 formative points

New tokens: earlier 1000000000000.125, later 1000000000000.130, in metres. Elapsed time is stipulated exactly 2 seconds. Each position reading has a separately supplied error bound of at most 0.0002 m; no stochastic independence or distribution is assumed. A fictional decision asks whether average displacement rate is definitely above 0.00255 m/s.

P1. (8 points) Derive the exact nominal displacement/rate and compare the checked float displacement 41/8192 with the exact nominal displacement. Give absolute/relative numerical errors and the nominal float rate.

P2. (8 points) Run the supplied project and recentered-project cases, or trace them explicitly. Reproduce into a second new folder and preserve source/output/hash evidence. Explain which comparisons should match and which provenance fields may differ. Actual execution has separate credit.

P3. (8 points) Derive physical displacement and rate intervals from the stated bounds. Make a justified decision about the threshold. Keep a numerical-error bound distinct from a measurement bound.

P4. (8 points) Compare full-token float subtraction, exact token subtraction and residual-token subtraction. Explain how to preserve the baseline and original tokens without claiming that subtracting a baseline after conversion restores information. Include one test that defeats a proposed universal repair.

P5. (8 points) Write a 150–220-word report with question, units, input model, numerical result, uncertainty, threshold conclusion, actual-versus-traced status, provenance and an unresolved limitation. Do not claim a real experiment, a supplied interpreter or a validated scientific instrument.

11. Delayed transfer

Return after a break without rereading the worked solution first.

D1. A counter stores exact integer ticks N+1 and N with N=2^53; each tick represents 0.002 seconds. Design a computation preserving their elapsed-time difference before any necessary float conversion. Explain why the original full-reading float workflow fails and how the unit conversion should be reported.

D2. Two sensors each have individual error bounds of 0.3 units. Derive a conservative difference bound. Then suppose a documented single shared offset is the only error in both sensors: what changes? Identify what extra evidence would be required before applying the second model.

References and limits

Official Python documentation supports the runtime semantics, not the original exercises or their scientific validity: floating-point tutorial, math.isclose and math.fsum, Fraction, and Decimal. Read on 4 November 2026. This package makes no claim of specialist moderation, calibrated marking, learner timing, screen-reader testing, institutional equivalence or completed semester delivery.