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

Unit 4: Algorithms, termination and numerical checking

TMP-SCI-204. Original teaching, following Units 1–3. This is not a new course, a supplied execution service, a qualification or an accredited programme. All data and models are fictional. Work in a folder you own, using an existing suitable Python interpreter if available. No installation, account, network, payment, instrument or private data is required. EXECUTION CAPACITY UNRESOLVED remains.

Preparation and route

Unit 3 showed why exact inputs, approximate arithmetic and scientific uncertainty must be distinguished. Now we ask: What does an algorithm promise, why will it stop, and what does its final status actually establish? A program ending is not enough. It may have exhausted its work budget without meeting the requested accuracy.

You need fractions, inequalities, substitution into an expression and Python functions/loops. We introduce every mathematical condition needed for the supplied root-finding task. No calculus is assumed. Proposed workload is 16 unpiloted hours: readiness/search 2; model and bracketing 3; bisection/termination 3; stopping rules/practice 3; quiz 1; project 3; delayed transfer 1. These are study estimates, not credit or measured learner timing.

By the end you should be able to specify a finite search, explain a loop invariant and stopping budget, justify a bracket, derive a midpoint error bound, distinguish successful convergence from budget exhaustion or float stagnation, verify a computation independently, and choose a simpler calculation when it answers the actual question.

R1. For the ordered readings [4,9,7,15,13], identify the first reading at least 12. Give its position counting from one and its Python index counting from zero.

R2. An interval is [1,2]. After three exact halvings, what is its width? What is the largest distance from its midpoint to any point in it?

R3. Substitute t=1 and t=2 into t²+2t-5. State the sign of each result.

R4. A program prints “finished after four steps.” What extra information is needed before claiming its requested numerical accuracy was reached?

1. Specify what “find” means

Consider five fictional readings in their original observation order: 4,9,7,15,13 response units. We want the first recorded reading at least 12, not the largest reading, not the first after sorting, and not the unobserved physical time at which a continuous signal crossed 12.

A linear search tests readings from left to right. At index 0, 4<12; at index 1, 9<12; at index 2, 7<12; at index 3, 15>=12. It returns index 3 and value 15 after four threshold comparisons. It does not need to test index 4 to decide which qualifying reading came first.

An invariant is a statement maintained while the loop runs. Immediately before testing index i, all earlier readings have been tested and are below the threshold. If the current reading qualifies, that invariant explains why it is the first hit. If no reading qualifies, reaching the end establishes that no hit exists in this finite list under this comparison rule. It says nothing about readings that were never recorded.

Termination has a separate argument. Each unsuccessful comparison advances the index by one; the number of untested readings decreases. A list of n readings permits at most n threshold comparisons. For an empty list there are zero comparisons and no hit. “No hit” is represented by None, not index zero, because zero is a valid first index.

The companion validates the whole list before searching. Thus invalid data after an early hit still cause rejection. Its comparisons field counts threshold decisions, not all validation work or CPU instructions. This distinction prevents a misleading performance claim: a reported single comparison does not mean the program touched only one input value in total.

G1. Trace searches of [4,9,7,15,13] for thresholds 12,15 and 16. Give result and comparison count. State the invariant and explain why sorting first changes the meaning of the task.

2. From recorded values to a supplied continuous model

A different task asks when a fictional smooth response reaches a target. The supplied model is R(t)=a t²+b t, with a=1 response unit per second squared and b=2 response units per second. When t is entered numerically in seconds, the program evaluates t*t + 2*t; its result is in response units. The code does not itself enforce physical units. They are part of our model contract.

Use 0<=t<=100 seconds. For the worked target 5, define the residual f(t)=R(t)-5. A root is a time r with f(r)=0. It is the crossing time predicted by this model, not automatically a measured event.

We need two different mathematical facts. First, the polynomial is continuous: small changes in t do not create jumps, and the function is defined throughout our interval. The intermediate value principle says that a continuous function with opposite endpoint signs has at least one zero between them. This is the reason a sign-changing interval can enclose a root; endpoint signs alone are insufficient without continuity.

Second, this model is strictly increasing on the stated nonnegative domain. For y>x>=0,

R(y)-R(x) = (y-x)(y+x+2).

Both factors are positive, so the difference is positive. Therefore the same target cannot be reached at two different times in this domain. Continuity gives existence within a valid sign-changing bracket, while strict increase gives uniqueness. These are related but distinct conclusions.

At t=1, f(1)=1+2-5=-2. At t=2, f(2)=4+4-5=3. Thus [1,2] brackets the unique worked root. Exact endpoint equality is a shortcut: if an endpoint already has zero residual, it is a root and no interval cuts are needed.

G2. Establish the bracket and uniqueness for target 5 on [1,2]. Then show why [2,3] is not a bracket for that target. Does rejecting [2,3] mean the model has no root anywhere?

3. Bisection preserves an enclosure

For the increasing model, keep lower and upper endpoints with f(lower)<=0 and f(upper)>=0. Let m=(lower+upper)/2. If f(m)=0, we have an exact root. If f(m)<0, the root is above m, so keep [m,upper]. If f(m)>0, keep [lower,m]. Each nonzero-residual decision discards half the interval while preserving the root.

The bisection invariant is: the root remains inside the current interval, with the lower endpoint at or below the target and the upper endpoint at or above it. We check this after every update, not just at the final answer. Copying the wrong endpoint would still shrink an interval, but could throw away the root. Shrinkage alone is not correctness.

The first six exact cuts for target 5 are:

  1. Midpoint 3/2, residual 1/4, keep [1,3/2].
  2. Midpoint 5/4, residual -15/16, keep [5/4,3/2].
  3. Midpoint 11/8, residual -23/64, keep [11/8,3/2].
  4. Midpoint 23/16, residual -15/256, keep [23/16,3/2].
  5. Midpoint 47/32, residual 97/1024, keep [23/16,47/32].
  6. Midpoint 93/64, residual 73/4096, keep [23/16,93/64].

The sixth trial midpoint is not the final reported midpoint. After the sixth cut, the companion reports the midpoint of the retained bracket: 185/128 seconds = 1.4453125 seconds. Keeping those two meanings separate prevents an off-by-one error when comparing a hand trace with program output.

G3. Reproduce the first three cuts independently. At each cut, explain the retained half using the sign and the model's increase, not a memorized left/right rule.

4. An error certificate and a finite stopping plan

If the true model root lies in [lower,upper], its distance from the interval midpoint is at most half the interval width. This is a geometric statement about an enclosure; it does not require knowing the root's decimal digits.

Let the initial width be W. After n nonzero-residual exact halvings, width is W/2^n. The midpoint error bound is W/2^(n+1). To guarantee an absolute time error at most epsilon, choose n so that W/2^(n+1)<=epsilon. You can find n by repeatedly halving the width; logarithms are optional and not needed by the companion.

With W=1 second and epsilon=1/128 second, six cuts suffice because half the final width is 1/128. Five cuts give bound 1/64, which is too wide. For epsilon=1/1000 second, nine cuts suffice: 1/1024<=1/1000, while the eight-cut bound 1/512 is larger. An exact-root shortcut may finish earlier; the count is a guarantee for the nonexact case, not a demand to continue after finding a root.

The companion uses three explicit statuses:

The work budget counts completed interval cuts, not all function evaluations. Exact endpoint or midpoint checks may succeed with a zero-cut budget. In particular target 8 on [1,3] has exact midpoint root 2 and can succeed without any cut. By contrast, target 5 on [1,2] with a zero-cut budget and tight tolerance returns budget exhaustion.

After only four cuts of the worked example, the bracket is [23/16,3/2]. Its midpoint is 47/32 and its error bound is 1/32, four times the requested 1/128. A valid JSON report or successful file-write exit code does not turn this numerical status into convergence. The lab intentionally records successful and unsuccessful numerical cases together.

G4. Derive the six-cut plan, then compare the four-cut and six-cut certificates. Explain how an algorithm can terminate safely yet fail to meet its requested accuracy.

5. Residual size answers a different question

A residual is a mismatch in response units, f(candidate)=R(candidate)-target. The coordinate error is a difference in seconds between the candidate and the unknown model root. They are not the same quantity or unit.

For the worked final midpoint 185/128, the exact residual is -335/16384 response units, about -0.02045. Its absolute size is greater than 1/128 numerically, yet the time-error certificate is still at most 1/128 second. Comparing those bare numbers as if they were the same error would mix units.

Nor does a tiny residual always imply tiny coordinate error. Multiply a residual function by 10^-12. Its roots do not move, but all residual values become a trillion times smaller. A tolerance chosen for the unscaled residual cannot be reused blindly. A valid conversion from residual to coordinate error needs information about how the model changes with its input. Our bracket certificate avoids needing such a conversion.

G5. For target 5, evaluate f(1), then g(1)=10^-12 f(1). Do the roots of g and f differ? Explain why accepting |g(1)|<10^-10 alone would not establish that time 1 is within 10^-10 seconds of the root.

6. Arithmetic and mathematical assumptions can break a naive loop

Our core bisection uses Fraction inputs and exact rational calculations on this polynomial. That keeps sign decisions and interval cuts exact within the bounded exercise. It does not mean rational arithmetic is free: numerators and denominators grow, and a cut count is not a complete runtime model. The fixed input bounds and cut budget keep this teaching computation finite.

A float implementation needs an additional failure check. On the checked radix-2, 53-significant-bit environment, let lower=1.0 and upper be the next representable float above it, 1.0000000000000002. The midpoint computed as lower + (upper-lower)/2 rounds to lower. There is no distinct representable float between those endpoints. An update that assigns lower=midpoint can leave the interval unchanged forever. A robust float workflow must detect no progress and return a distinct failure or use another justified strategy; it must not label stagnation as convergence.

Mathematical conditions also matter. The function h(t)=1/(t-1) has opposite signs at 0 and 2, but it is undefined at 1 and has no zero. Treating that discontinuity as a root would be wrong. Conversely, k(t)=(t-1)² has a zero at 1 while its values at 0 and 2 are both positive. A general failure to find opposite endpoint signs does not prove that every possible function has no root.

The companion deliberately solves only the supplied continuous increasing model. It does not accept arbitrary functions, simulate physical measurements or validate a new scientific model. If the model changes, its domain, continuity, sign behavior, arithmetic and stopping rule need review.

G6. Explain the float-stagnation example and the two mathematical counterexamples. For each, identify the assumption that failed rather than merely saying “the code is wrong.”

7. Execute and inspect the right evidence

Keep bounded_algorithms.py and test_bounded_algorithms.py together. Use an existing Python 3.9 or later interpreter; the float-spacing demonstration needs math.nextafter. If none is available, use the labelled tracing route without installing anything. Record your interpreter version. From the package folder run:

python3 --version
python3 -B -m unittest discover -v
python3 -B bounded_algorithms.py my-bounded-run-001

Use the verified command available to you, such as py where appropriate. The author used Python 3.12.14. If you cannot execute, prepare traces and test designs marked predicted. Do not claim the author's checks as your execution.

The runner makes a new directory containing report.json, a snapshot bounded_algorithms.py, and a final run.json with environment, arguments and hashes of the two known payload files. Fixed example inputs are preserved in the source snapshot. Existing directories are refused; a later write failure can leave partial output. Preserve that evidence and use a new directory for a justified retry. A parseable completion manifest with matching hashes establishes byte consistency, not scientific truth, authenticity, or an atomic/crash-proof transaction. Use trusted owned paths and do not edit source during a run.

Reproduce with python3 -B my-bounded-run-001/bounded_algorithms.py my-bounded-run-002. Under the same checked conditions report bytes should match; invocation/output path fields may differ. Independently inspect the bracket signs, midpoint bound and numerical status. The report's short_budget case is expected to say budget_exhausted; this is a checked example, not a failed file-writing command.

For a changed case, save a separate script beside the module:

from fractions import Fraction
from bounded_algorithms import bisect_response
print(bisect_response(7, 1, 2, Fraction(1,256), 7))

The solver accepts exact built-in integers or Fraction objects, not floats or booleans. Targets are 0–10200 response units; endpoints are 0–100 seconds with lower<upper; tolerance is positive and at most 100 seconds; input denominators are at most 10^9. Budgets are integers 0–200. These are exercise limits, not physical instrument capacities. Search inputs are a list of at most 1000 integer readings in 0–10^6, with an integer threshold in that range. Empty lists are valid. Invalid entries anywhere are rejected before searching.

8. Independent practice and audit

I1. Search [4,14,3,12] for the first value at least 10. Explain why you may not discard an arbitrary half of this unsorted list as though it were a continuous monotone response model.

I2. With initial interval width 3 seconds and tolerance 1/100 second, find the least guaranteed number of nonexact cuts. Show that one fewer does not suffice.

I3. Target 8 on [1,3] has a zero-cut budget and tight positive tolerance. Predict the status, candidate and cut count. Explain why zero cuts does not mean zero function evaluations.

I4. An implementation updates upper=midpoint when the midpoint residual is negative in our increasing model. Use the first negative midpoint of the worked trace to demonstrate loss of the root-enclosure invariant.

I5. Design four tests covering no finite-data hit, an exact root, a nonconverged but valid bracket, and invalid input after an early search hit. Give independent expectations.

I6. Someone reports “bisection is twice as fast” after one run used half as many cuts. Give at least three reasons this is not a justified general runtime claim, and propose a more careful bounded comparison.

H1. “The program exited successfully and wrote complete JSON, so every numerical case converged.” Refute using the report.

H2. “A sign change always proves a root, and no sign change always proves there is no root.” Give a different counterexample to each half.

H3. “The error bound is 1/1000, so the physical crossing time is known that accurately.” Identify what the algorithm does and does not establish about the model and real measurements.

9. Changed-target quiz: 30 formative points

Use R(t)=t²+2t with target 7 response units, initial bracket [1,2] seconds and requested time-error bound 1/256 second. Each task is worth 6 points.

Q1. Verify the initial signs/uniqueness and derive the guaranteed cut budget without knowing the root's decimal expansion.

Q2. After seven cuts, inspect bracket [117/64,235/128]. Verify endpoint residual signs, derive the reported midpoint/error bound and decide whether the tolerance is met.

Q3. Evaluate the scaled residual 10^-12(R(1)-7). Explain why its small magnitude alone does not certify that time 1 is accurate to 10^-10 seconds.

Q4. With only six allowed cuts, predict the appropriate convergence claim. Separately explain what happens if a float midpoint equals an endpoint before the requested bound is reached.

Q5. Execute or explicitly trace the quiz case and one discriminating comparison. Preserve source, prediction, status, output or labelled prediction, test and limitation. Do not substitute the author's run for yours.

10. Project: answer the actual crossing-time question, 40 formative points

The new target is 11 response units, interval [2,3] seconds and requested midpoint error at most 1/1000 second. A separate decision asks whether the model reaches the target strictly before 2.464 seconds.

P1. (8 points) Establish a bracket/unique root and choose the least guaranteed nonexact cut budget. Explain the invariant, finite stopping argument and expected success criterion.

P2. (8 points) Run and reproduce the supplied project case, or explicitly trace it. Verify bracket [1261/512,631/256], midpoint 2523/1024, residual and error certificate. Keep real source/output/hash evidence if executed.

P3. (8 points) Decide what the returned bracket alone establishes about “strictly before 2.464.” Then evaluate the residual exactly at 2.464=308/125 and use monotonicity to answer the decision without more bisection. Explain why this is a different calculation chosen for the actual question.

P4. (8 points) Compare a sufficient and insufficient cut budget, an exact-root shortcut and a non-progress float case. Design independent tests for honest statuses. State what would need rechecking if an arbitrary new response function replaced the polynomial.

P5. (8 points) Write a 150–220-word report with model/domain/units, result, certificate, stopping status, decision, actual-versus-traced evidence and limits. Explain why a mathematical model decision is not a measured physical guarantee.

11. Delayed transfer

D1. A sorted list [2,5,8,11,14] is searched for exact value 8. Explain why discarding half can be justified here, unlike I1's unsorted first-hit task. State the changed invariant and a stopping condition; do not claim that continuous-function bisection and discrete search have identical contracts.

D2. A different continuous function has opposite endpoint signs but several roots in the interval. What part of bisection's root-enclosure argument can remain valid, and which uniqueness/first-crossing conclusions no longer follow?

Reference and delivery boundaries

Official SciPy bisection documentation supports the general continuity/sign-change and explicit stopping-budget context. No SciPy installation or call is used, and its tolerance/API rules are not claimed to be this companion's rules. Python's Fraction documentation and nextafter documentation support the library operations. Opened 4 November 2026. Original model, proofs, packets, examples and assessments were independently checked. Specialist moderation, learner timing/calibration, actual assistive-technology tests and learner execution access remain unresolved. The reader and optional companion files are available; they do not provide an interpreter. No accreditation, credit or institutional-equivalence claim.