# Worksheet: Engineering algorithms

*Tactiverge Academy · Computational Engineering, module 2 · https://tactiverge.win/academy/computational-engineering/#engineering-algorithms*

Name: ______________________    Date: ____________

## Learning objectives

Tick each one when you can do it without looking at your notes.

- [ ] Describe an algorithm precisely enough that someone else could follow it.
- [ ] Implement linear and binary search and compare how their run time grows.
- [ ] Find the root of an equation numerically using bisection.
- [ ] Explain the difference between an exact and an approximate (numerical) answer.

## Lesson 1: Algorithms and complexity

What makes a method an algorithm, how to count the steps it takes, and how big-O notation predicts whether it will still be fast when the problem grows.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/algorithms-and-complexity/

### Check your understanding

1. An algorithm does 3n + 20 steps for an input of size n. What is its big-O?
   A) O(1)
   B) O(n)
   C) O(n²)
   D) O(3n + 20)

2. An O(n²) method takes 2 seconds for 1,000 items. Roughly how long for 10,000 items?
   A) 20 seconds
   B) 4 seconds
   C) 200 seconds
   D) 2,000 seconds

3. Why do engineers usually quote the worst case?
   A) Because the worst case is the most common
   B) Because a system must meet its deadline even on the hardest input it may receive
   C) Because the best case cannot be calculated
   D) Because big-O is only defined for the worst case

4. Which change made the duplicate-ID check so much faster?
   A) Using a faster computer
   B) Writing the loops in a different order
   C) Storing seen IDs in a set, so each membership check takes roughly constant time
   D) Testing a smaller list

5. For an O(log n) algorithm, what happens to the work when n doubles?
   A) It doubles
   B) It quadruples
   C) It stays exactly the same
   D) It grows by about one step

#### Project: Programming project: measure growth

Investigate how step counts grow, using Python and a sheet of graph paper (or a free spreadsheet).

1. Use `count_pair_checks` from this lesson for n = 10, 20, 40, 80, 160 and record the results. Each time n doubles, what happens to the count?
2. Write a function that counts the steps to sum a list of n numbers, and record it for the same values of n.
3. Plot both on the same axes. Describe the shapes in a sentence each.
4. Use `time.perf_counter()` to time `has_duplicate_pairs` and `has_duplicate_set` on worst-case lists of 1,000, 2,000 and 4,000 IDs. Repeat each timing three times and note how much it varies. Do the timings grow the way the step counts predict?

No hardware is required.

**Deliverables**

- A table of step counts for both functions and a hand-drawn or spreadsheet plot
- Timings for the two duplicate checks, with repeats
- A paragraph comparing your measurements with the big-O predictions

### My notes

______________________________________________

______________________________________________

## Lesson 2: Searching and sorting

Find things in data quickly: linear search, binary search on sorted data, a simple sorting algorithm traced by hand, and why sorting first often pays off.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/searching-and-sorting/

### Check your understanding

1. What must be true of a list before binary search gives correct results?
   A) It must contain only integers
   B) It must be sorted
   C) It must have an even number of items
   D) It must contain no more than 1,000 items

2. About how many steps does binary search need, at most, for a sorted list of 1,000,000 items?
   A) About 20
   B) About 1,000
   C) About 500,000
   D) About 1,000,000

3. Insertion sort is given a list that is already almost in order. How does it perform?
   A) It is at its worst, O(n²)
   B) It cannot handle sorted input
   C) It is close to O(n), because each item moves only a short distance
   D) It always takes exactly n log n steps

4. You need to look up 10,000 different values in an unsorted list of 1,000,000 readings. What is the best plan?
   A) Run linear search 10,000 times
   B) Sort the list once, then use binary search for each value
   C) Use binary search on the unsorted list
   D) Sort the list again before every search

5. Why is the median often a better 'typical value' than the mean for sensor data with occasional glitches?
   A) The median is always larger
   B) The median is easier to calculate on unsorted data
   C) The median uses every value equally
   D) A single extreme value barely changes the median, but it can shift the mean a lot

#### Project: Programming project: aligning two sensor logs

Two made-up sensor logs were recorded at different rates: a camera log with a timestamp every 33 ms and a force log with a timestamp every 10 ms, both starting at 0 and lasting 10 seconds. Create them in Python as sorted lists of timestamps in milliseconds.

1. For each camera timestamp, find the force timestamp closest to it. Do it first with linear search, then with `bisect.bisect_left` (check the item at the returned position and the one before it).
2. Count the total comparisons made by your linear method, and time both methods with `time.perf_counter()`.
3. Check that both methods give identical matches.
4. Write your own `insertion_sort` and test it against `sorted` on 20 random lists (use the `random` module), including an empty list and a list with repeated values.

No hardware is required.

**Deliverables**

- A Python 3 program that matches each camera timestamp to the nearest force timestamp in two ways
- Comparison counts and timings for both methods
- Test output showing insertion_sort agrees with sorted

### My notes

______________________________________________

______________________________________________

## Lesson 3: Numerical root finding

Solve equations that have no neat formula: the bisection method, which always works if you can bracket a root, and Newton's method, which is far faster but can fail.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/root-finding/

### Check your understanding

1. Bisection on an interval of width 8 runs for 3 steps. How wide is the bracket now?
   A) 5
   B) 2
   C) 1
   D) 0.5

2. Which condition must hold before bisection can start on [a, b]?
   A) f(a) and f(b) have opposite signs
   B) f(a) = f(b)
   C) The derivative of f is known
   D) a and b are both positive

3. Newton's method uses which formula for the next guess?
   A) x_next = (a + b) / 2
   B) x_next = x + f(x) × f′(x)
   C) x_next = f(x) / x
   D) x_next = x − f(x) / f′(x)

4. Newton's method starting at x = 0 alternates 0, 1, 0, 1, … for one equation. What is the best response?
   A) Let it run longer; it will settle eventually
   B) Stop at the step limit, then try a different start or use bisection on a bracket
   C) Accept 0.5 as the root
   D) Newton's method cannot cycle, so the code must be wrong

5. Why compute the residual f(x) at the answer?
   A) It confirms the answer really makes f close to zero
   B) It makes the method converge faster
   C) It gives the derivative
   D) It is needed to start bisection

#### Project: Programming project: a root-finding race

Compare bisection and Newton's method on paper and in Python.

1. By hand, with a calculator, do four steps of bisection for x² − 5 = 0 on [2, 3], and three steps of Newton's method starting at x = 2. Record each guess.
2. In Python, solve the same equation with both methods to a tolerance of 10⁻¹⁰. Print the guesses at each step and the number of steps.
3. Solve cos(x) = x (rewrite it as f(x) = cos(x) − x). Find a bracket by tabulating f at x = 0, 0.25, 0.5, … , 1.5 first.
4. Try Newton's method on x³ − 2x + 2 = 0 from x = 0 and from x = −2. Describe what happens, and use bisection to find the real root reliably.

No hardware is required.

**Deliverables**

- Hand-worked tables of guesses for both methods
- A Python 3 program with both root finders and printed step-by-step output
- A short paragraph comparing speed and reliability, using your results

### My notes

______________________________________________

______________________________________________

## Lesson 4: Numerical integration and differentiation

Turn sampled data into totals and rates: the trapezoid rule for distance from speed, finite differences for speed from position, and how step size and noise create error.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/numerical-integration-differentiation/

### Check your understanding

1. Speeds of 0.2 m/s and 0.4 m/s are measured 0.5 s apart. What distance does the trapezoid rule give for that interval?
   A) 0.30 m
   B) 0.15 m
   C) 0.10 m
   D) 0.60 m

2. Doubling the number of trapezoids on a smooth function reduced the error by about a factor of four. What does this tell you?
   A) The method has a bug
   B) The error is proportional to h
   C) The error is proportional to h², so the method is second order
   D) The error is independent of h

3. Why is the central difference usually more accurate than the forward difference for the same h?
   A) It looks equally far on both sides, so the leading error terms cancel
   B) It uses fewer function evaluations
   C) It divides by a smaller number
   D) It only works on straight lines

4. Making h extremely small (such as 10⁻¹³) made the derivative estimate worse. Why?
   A) The sine function is not defined for small numbers
   B) Python rounds h to zero
   C) Smaller steps always increase approximation error
   D) Subtracting two nearly equal floats loses most significant digits, and the rounding error is then divided by a tiny number

5. Position readings have 0.5 mm of noise and are taken every 10 ms. What happens when you differentiate them to get speed?
   A) The noise disappears
   B) The noise is amplified, because the difference is divided by a small time step
   C) The speed is exact as long as the robot moves steadily
   D) The noise is converted into a constant offset

#### Project: Programming project: from speed to distance and back

Create a made-up speed log for a robot that speeds up, cruises and slows down, with samples every 0.1 s for 10 s. Use a formula, so you also know the exact distance (for example, constant acceleration phases, where the distance can be worked out by hand from areas of triangles and rectangles).

1. Integrate the speed log with the trapezoid rule and compare with your exact distance. Repeat using every second, fifth and tenth sample only. How does the error change?
2. Integrate to get position at every sample, then differentiate the positions with forward and central differences. Compare with the original speeds.
3. Add made-up noise to the positions using `random.uniform(-0.001, 0.001)` (call `random.seed(1)` first so your results repeat). Differentiate again, then try smoothing the positions with a 5-sample moving average first.
4. Summarise what you learned about integrating and differentiating real data in a short paragraph.

No hardware is required.

**Deliverables**

- A Python 3 program with trapezoid integration and two finite-difference methods
- A table of distance errors for different sampling intervals
- Printed or plotted speeds recovered from noisy and smoothed positions, with a short discussion

### My notes

______________________________________________

______________________________________________

## Lesson 5: Path planning on grids

Find routes for a mobile robot on a grid map: breadth-first search for the fewest moves, Dijkstra's algorithm for the cheapest route, and A*, which uses a heuristic to search less.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/path-planning-on-grids/

### Check your understanding

1. What does breadth-first search guarantee on a grid where every move costs the same?
   A) It finds a path with the fewest moves, if one exists
   B) It always expands fewer cells than A*
   C) It finds the path that avoids sand
   D) It never needs a visited set

2. Why did Dijkstra's algorithm choose a 15-move route when BFS found an 11-move one?
   A) Dijkstra's algorithm has a bug
   B) The 11-move route crossed sand, so it cost 23, while the 15-move route cost only 15
   C) Dijkstra's algorithm always prefers longer routes
   D) BFS cannot see the top row

3. In A*, a cell's priority is…
   A) its estimated distance to the goal only
   B) the number of times it has been visited
   C) its row number plus its column number
   D) the cost to reach it so far plus an estimate of the cost from it to the goal

4. A heuristic is 'admissible' if…
   A) it never overestimates the true remaining cost
   B) it is always exactly correct
   C) it is larger than the true cost
   D) it uses diagonal moves

5. Why do planners often inflate obstacles on the map before planning?
   A) To make the map look tidier
   B) To reduce the number of cells
   C) So a path through free cells keeps the robot's whole body, not just its centre, clear of obstacles
   D) Because A* only works with large obstacles

#### Project: Project: a planner of your own

**On paper.** Draw a 6 × 8 grid with a start, a goal and a few walls. Run BFS by hand: write 0 in the start cell, 1 in every free neighbour, 2 in their unvisited free neighbours, and so on until you reach the goal. Then trace the path back by stepping to any neighbour with a number one smaller.

**In Python.** Copy `gridmap.py` and the two planners from this lesson, then:

1. Design your own map of at least 10 × 15 cells, including a region of costly cells. Check that BFS, Dijkstra and A* behave as you expect, and record moves, cost and cells expanded for each.
2. Make the goal unreachable by surrounding it with walls. Make sure your program prints a clear message instead of crashing.
3. Multiply the heuristic by 3. Does A* still find the cheapest path? How many cells does it expand?
4. Add diagonal moves with a cost of 1.4, and explain in a sentence why the Manhattan distance is no longer admissible for this case.

No hardware is required.

**Deliverables**

- A photo or scan of your hand-worked BFS grid
- A Python 3 program and a table comparing the three algorithms on your map
- Short answers to steps 3 and 4

### My notes

______________________________________________

______________________________________________

## Lesson 6: Optimisation basics

Choose the best design or setting systematically: define an objective function, search it by brute force, descend its slope with gradient descent, and beware of local minima.

Read online: https://tactiverge.win/academy/computational-engineering/engineering-algorithms/optimisation-basics/

### Check your understanding

1. In the sensor calibration example, what is the objective function?
   A) The list of raw readings
   B) The sum of squared differences between k × reading and the true distances
   C) The scale factor k
   D) The number of measurements

2. Gradient descent finds slope(k) = +40 at the current k. Which way should k move?
   A) Increase k, because the slope is positive
   B) Leave k unchanged
   C) Decrease k, because the error rises as k increases
   D) Set k to 40

3. With a step size of 10⁻⁵, k shot off to about −77,906. What happened?
   A) The method found a better minimum
   B) The data must contain an error
   C) The step size was too small
   D) The step size was so large that each step overshot the minimum by more than the last, so the method diverged

4. Gradient descent started at x = 2 settles at x ≈ 1.13, but f is lower at x ≈ −1.30. Why?
   A) x ≈ 1.13 is a local minimum, and gradient descent only moves downhill from where it starts
   B) Gradient descent always finds the global minimum, so the code is wrong
   C) The function has no minimum
   D) The step size was too large

5. Grid search over 100 values per variable is cheap for one variable. Roughly how many evaluations does it need for 4 variables?
   A) 400
   B) 10,000
   C) 100,000,000
   D) 1,000,000,000,000

#### Project: Programming project: tune it yourself

Use optimisation to choose two parameters.

1. Extend the calibration model to distance ≈ k × reading + c, where c is an offset. Make up six measurements (label them as made-up) and write an error function of both k and c.
2. Find the best k and c by grid search over a sensible range. Count the number of error evaluations.
3. Implement gradient descent for both variables at once: compute the slope with respect to k and with respect to c (you can estimate each with a central difference), and update both at every step. Try at least three step sizes and record what happens.
4. For f(x) = x⁴ − 3x² + x, run gradient descent from 21 starting points between −3 and 3. Count how many end in each valley.
5. Write a paragraph on which method you would trust more, and why, for a problem with 10 variables.

No hardware is required.

**Deliverables**

- A Python 3 program with grid search and gradient descent for the two-parameter calibration
- A table of results for different step sizes
- The count of starts ending in each valley, and your paragraph

### My notes

______________________________________________

______________________________________________

---

## Answer key (for self-checking after you try)

**Lesson 1: Algorithms and complexity**

1. B — Big-O keeps only the fastest-growing term and drops constant factors, so 3n + 20 is O(n): doubling n roughly doubles the work.
2. C — Ten times the input gives about 10² = 100 times the work for a quadratic method, so about 2 × 100 = 200 seconds.
3. B — A controller that is usually fast but occasionally far too slow will still fail when that occasional input arrives, so designers plan for the worst case.
4. C — The set lets the algorithm check each ID once, giving O(n) instead of comparing every pair, which is O(n²). It uses extra memory to save time.
5. D — log₂(2n) = log₂ n + 1, so doubling the input adds only about one step. That is why logarithmic algorithms stay fast on huge inputs.

**Lesson 2: Searching and sorting**

1. B — Binary search discards half the list by comparing with the middle item. That decision is only valid if every item before the middle is smaller and every item after is larger.
2. A — Each step halves the range, and 2²⁰ is just over a million, so about 20 steps are enough.
3. C — Each new item stops sliding as soon as it meets a smaller one. In nearly sorted data that happens almost immediately, so the work is close to one pass.
4. B — Sorting costs O(n log n) once; each binary search then costs only about 20 steps. Ten thousand linear searches could cost up to ten billion comparisons.
5. D — The median is the middle value of the sorted data, so a single huge glitch only moves it by at most one position. The mean adds the glitch in directly.

**Lesson 3: Numerical root finding**

1. C — Each step halves the width: 8 → 4 → 2 → 1. After n steps the width is the original divided by 2ⁿ.
2. A — Opposite signs at the ends guarantee that a continuous f crosses zero somewhere in between, so the bracket really contains a root.
3. D — It follows the tangent line at x down to where it crosses zero, which gives x − f(x)/f′(x).
4. B — A cycle never converges. A step limit detects the failure; a better starting guess, or a bracketing method, provides a reliable answer.
5. A — A small residual is direct evidence that the returned value is a root. A large one reveals a bug, a bad bracket or a method that stopped too early.

**Lesson 4: Numerical integration and differentiation**

1. B — ½ × (0.2 + 0.4) × 0.5 = 0.15 m: the average speed multiplied by the time step.
2. C — Halving h and seeing the error fall by 2² = 4 is the signature of a second-order method.
3. A — The symmetric formula cancels the first-order error term, leaving an error proportional to h² rather than h.
4. D — This is called cancellation. Floats have about 16 significant digits, so very small differences are dominated by rounding error.
5. B — A 1 mm difference between noisy readings divided by 0.01 s is 0.1 m/s of error. Differentiation amplifies noise, so smoothing or longer intervals are needed.

**Lesson 5: Path planning on grids**

1. A — BFS explores cells in order of their number of moves from the start, so the first time it reaches the goal it has used the fewest possible moves.
2. B — Dijkstra minimises total cost, not the number of moves. With sand costing 5 per cell, the longer route is cheaper.
3. D — A* combines what is known (cost so far) with an estimate of what remains, which steers the search towards the goal.
4. A — An estimate that never overestimates keeps A* from wrongly ignoring the cheapest route, so A* still returns an optimal path.
5. C — Grid planners treat the robot as a point. Growing each obstacle by the robot's radius makes the point-sized plan safe for a robot of real size.

**Lesson 6: Optimisation basics**

1. B — The objective is the single number being minimised. Here it measures how badly a given k fits the data; k itself is the decision variable.
2. C — A positive slope means the error goes up as k goes up, so moving downhill means decreasing k. The update k − rate × slope does exactly that.
3. D — A step that is too large jumps past the valley floor to a point that is even higher up, and the errors grow every step. Reducing the step size fixes it.
4. A — From x = 2, every downhill step leads into the nearer valley. Reaching the deeper one would require going uphill first, which gradient descent never does.
5. C — Every combination must be tried: 100 × 100 × 100 × 100 = 100⁴ = 10⁸ evaluations. Grid search grows exponentially with the number of variables.

---

This work is licensed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/. Attribute as: Tactiverge Academy, https://tactiverge.win.
