Algorithms
This page collects the algorithms met in VCE Maths, grouped by what they do. Each one starts with a short introduction and the algorithm in structured English: numbered steps, indented like the code they become, so each step can be turned into a line or two of pseudocode. There are three kinds.
- Samples show the whole program: the pseudocode beside the Python that Translate writes for it, line by line. Most are in the app under Doc ▸ Examples: run one and step through its trace table to see it work.
- Exercises give a test case to check your program against, and a hint or starter code with gaps (
???) to fill in. Type the starter into the Code pane, complete it, and run it. - Translation exercises give the Python and a pseudocode starter: write the pseudocode, then switch the Code pane to Python to compare.
Lists count from 1 in pseudocode and from 0 in Python, so an index can differ by one between the columns: the translation takes care of that. See Pseudocode syntax for everything the app accepts, and Pseudocode & Python for running and tracing.
Numbers and sequences#
Fibonacci numbers (sample)#
Doc ▸ Examples ▸ Intro ▸ Loop
Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, … The program keeps only the last two numbers, a and b, and moves them along the sequence once per pass of the loop.
Inputs:
- terms : how many new numbers to make
Structured English:
- Start with a = 0 and b = 1.
- Repeat
termstimes:- Make the next number, c = a + b.
- Move along one place: a takes b's value, then b takes c's.
- Print b, the last number made.
| Pseudocode | Python |
|---|---|
terms ← 10 |
terms = 10 |
a ← 0 |
a = 0 |
b ← 1 |
b = 1 |
for i from 1 to terms |
for i in range(1, terms + 1): |
c ← a + b |
c = a + b |
a ← b |
a = b |
b ← c |
b = c |
end for |
|
print b |
print(b) |
Greatest common divisor and lowest common multiple (sample)#
Doc ▸ Examples ▸ Number theory ▸ GCD and LCM
Euclid's algorithm finds the greatest common divisor (GCD) of two whole numbers without listing their factors. The lowest common multiple then follows from LCM(a, b) = a × b ÷ GCD(a, b). For 84 and 30 the pairs are (84, 30), (30, 24), (24, 6), (6, 0), so the GCD is 6 and the LCM is 420.
Inputs:
- a, b : two whole numbers
Structured English:
- While b is not 0:
- Let r be the remainder when a is divided by b.
- Replace a with b, and b with r.
- The GCD is a.
- The LCM is a × b ÷ GCD, using the original a and b.
| Pseudocode | Python |
|---|---|
define gcd(a, b) |
def gcd(a, b): |
while b ≠ 0 do |
while b != 0: |
// r: the remainder when a is divided by b |
# r: the remainder when a is divided by b |
r ← a mod b |
r = a % b |
a ← b |
a = b |
b ← r |
b = r |
end while |
|
return a |
return a |
end |
|
a ← 84 |
a = 84 |
b ← 30 |
b = 30 |
g ← gcd(a, b) |
g = gcd(a, b) |
print g |
print(g) |
print (a*b) div g |
print(a * b // g) |
Prime numbers: the sieve of Eratosthenes (sample)#
Doc ▸ Examples ▸ Number theory ▸ Prime sieve (1 to 100)
A sieve finds every prime up to n at once, by crossing out multiples instead of testing each number. Its list is about the numbers themselves (is_prime[k] is about k), so the program starts with the comment // index from 1: then Translate keeps the Python's loops counting the same numbers (see Pseudocode syntax).
Inputs:
- n : the largest number to check
Structured English:
- Mark every number from 1 to n as prime, then unmark 1.
- For each number p from 2 to n:
- If p is still marked:
- Unmark p², p² + p, p² + 2p, … up to n. (Smaller multiples of p were unmarked by smaller primes.)
- If p is still marked:
- The numbers still marked are the primes: print them.
| Pseudocode | Python |
|---|---|
// index from 1: is_prime[k] says whether k is prime |
# index from 1: is_prime[k] says whether k is prime |
n ← 100 |
n = 100 |
is_prime ← [] |
is_prime = [] |
for i from 1 to n |
for i in range(1, n + 1): |
append true to is_prime |
is_prime.append(True) |
end for |
|
is_prime[1] ← false |
is_prime[0] = False |
for p from 2 to n |
for p in range(2, n + 1): |
if is_prime[p] then |
if is_prime[p - 1]: |
// m: each multiple of p, from p² up |
# m: each multiple of p, from p² up |
m ← p*p |
m = p * p |
while m ≤ n do |
while m <= n: |
is_prime[m] ← false |
is_prime[m - 1] = False |
m ← m + p |
m = m + p |
end while |
|
end if |
|
end for |
|
primes ← [] |
primes = [] |
for i from 2 to n |
for i in range(2, n + 1): |
if is_prime[i] then |
if is_prime[i - 1]: |
append i to primes |
primes.append(i) |
end if |
|
end for |
|
print primes |
print(primes) |
Factorial (exercise)#
The factorial n! = 1 × 2 × 3 × … × n counts the ways to arrange n different things in a row.
Structured English:
- Start a running product at 1.
- For each k from 1 to n:
- Multiply the product by k.
- The product is n!.
Test case: 5! = 120, 10! = 3628800 and 20! = 2432902008176640000.
Starter:
define factorial(n)
product ← 1
for k from 1 to ???
product ← ???
end for
return product
end
print factorial(5)
Extension: write it again without a loop, using n! = n × (n − 1)! and 0! = 1 (a function that calls itself).
Collatz sequence (exercise)#
The Collatz sequence is a famous unsolved problem: nobody has proved that it always reaches 1, but it has for every number tried. It is a natural while loop, because you cannot know in advance how many steps it takes.
Structured English:
- Start with a whole number n, and a step count of 0.
- While n is not 1:
- If n is even, halve it.
- Otherwise, replace n with 3n + 1.
- Print n and add 1 to the step count.
- Print the step count.
Test case: starting at 6 the sequence is 6, 3, 10, 5, 16, 8, 4, 2, 1, which is 8 steps. Starting at 27 takes 111 steps.
Hint: n mod 2 = 0 is true when n is even, and n div 2 halves an even number exactly.
Writing a number in another base (exercise)#
Computers store numbers in base 2 (binary) and often show them in base 16 (hexadecimal). Converting between bases uses division with remainder.
Inputs:
- n : the number
- b : the base
Structured English:
- Start with an empty list of digits.
- While n is more than 0:
- Add the remainder of n ÷ b to the list: it is the next digit, from the right.
- Replace n with the whole-number quotient of n ÷ b.
- The digits, read in reverse order, are n in base b.
Test case: 37 in base 2 is 100101; 255 in base 16 is FF (digits 15 and 15); 2026 in base 16 is 7EA (digits 7, 14 and 10).
Starter:
define to_base(n, b)
digits ← []
while n > 0 do
append ??? to digits
n ← ???
end while
return digits
end
print to_base(37, 2)
This prints the digits last first: [1, 0, 1, 0, 0, 1]. Then write a loop that builds the list the right way round.
ISBN check digit (exercise)#
A 13-digit ISBN ends with a check digit, chosen so that typing mistakes are caught. Supermarket barcodes (EAN-13) use the same rule.
Structured English:
- Start a total at 0.
- For each position i from 1 to 13:
- If i is odd, add the digit to the total.
- Otherwise, add three times the digit.
- The ISBN is valid when the total is a multiple of 10.
Test case: 978-3-16-148410-0 is valid. Change its last digit to 1 and it is invalid.
Starter:
define check_isbn13(d)
total ← 0
for i from 1 to 13
if i mod 2 = 1 then
total ← ???
else
total ← ???
end if
end for
return total mod 10 = 0
end
print check_isbn13([9, 7, 8, 3, 1, 6, 1, 4, 8, 4, 1, 0, 0])
Solving equations (root finding)#
Each method here finds an x with f(x) = 0, to a chosen accuracy, when algebra cannot.
Linear search for a sign change (exercise)#
The simplest method: step along the x-axis until the graph crosses it. A continuous function that changes sign between two x values has a zero between them.
Inputs:
- f : the function to find a zero of
- x0 : the starting value of x
- h : the step size
Structured English:
- Start at x = x0 and work out y = f(x).
- Repeat:
- Keep the old y.
- Step x along by h and work out the new y.
- Until the old y and the new y have opposite signs (their product is 0 or less).
- The zero is between x − h and x.
Test case: for x⁴ − x − 1 = 0, starting at 0 with steps of 0.25, the zero is between 1 and 1.25 (it is 1.2207…).
Starter:
define f(x)
return x^4 - x - 1
end
h ← 0.25
x ← 0
y ← f(x)
repeat
y_old ← y
x ← ???
y ← f(x)
until y_old × y ≤ 0
print "zero between", x - h, "and", x
Bisection (sample)#
Doc ▸ Examples ▸ Numerical methods ▸ Bisection
Bisection traps a zero between a and b, where f has opposite signs, and halves the gap each pass. It is slow but it never fails once a sign change is found. Here f(x) = x² − 2, so the program closes in on √2.
Inputs:
- f : the function, with f(a) < 0 < f(b)
- a, b : the ends of the interval
- precision : how narrow the interval must become
Structured English:
- While the interval is wider than the precision:
- Find its midpoint, c = (a + b) ÷ 2.
- If f(c) is negative, the zero is to the right of c: move a up to c.
- Otherwise the zero is to the left of c: move b down to c.
- Print c.
| Pseudocode | Python |
|---|---|
define f(x) |
def f(x): |
return x*x - 2 |
return x * x - 2 |
end |
|
precision ← 0.001 |
precision = 0.001 |
a ← 1 |
a = 1 |
b ← 2 |
b = 2 |
while b-a > precision |
while b - a > precision: |
c ← (a+b)/2 |
c = (a + b) / 2 |
if f(c) < 0 then |
if f(c) < 0: |
a ← c |
a = c |
else |
else: |
b ← c |
b = c |
end if |
|
end while |
|
print c |
print(c) |
False position (exercise)#
False position (regula falsi) keeps bisection's safe bracket, but instead of the midpoint it uses where the chord joining (a, f(a)) and (b, f(b)) crosses the x-axis. When the graph is nearly straight there, that point is much closer to the zero than the midpoint is.
Inputs:
- f : the function, with f(a) and f(b) of opposite signs
- a, b : the ends of the interval
Structured English:
- Repeat 8 times:
- Find where the chord crosses the x-axis: c = b − f(b) × (b − a) ÷ (f(b) − f(a)).
- If f(a) and f(c) have opposite signs, the zero is between a and c: move b to c.
- Otherwise it is between c and b: move a to c.
- Print c.
Test case: for f(x) = x³ − 2x − 5 on [2, 3] the guesses are 2.05882, 2.08126, 2.08964, … and the 8th is 2.09452. They creep up on the zero, 2.09455, from one side, because one end of the bracket never moves. Compare Newton's method below on the same cubic.
Starter:
define f(x)
return x³ - 2x - 5
end
a ← 2
b ← 3
for i from 1 to 8
c ← ???
if f(a)×f(c) < 0 then
b ← ???
else
a ← ???
end if
print c
end for
Newton's method (sample)#
Doc ▸ Examples ▸ Numerical methods ▸ Polynomial + Newton
Newton's method follows the tangent at the current guess down to the x-axis, and uses where it lands as the next guess. Near a zero it is very fast: the number of correct digits roughly doubles each step. This sample stores a polynomial as its list of coefficients (x³ − 2x − 5 is [1, 0, -2, -5]), so poly can work out its value at any x and derivative can find the derivative's coefficients.
Inputs:
- f : the polynomial's coefficients
- x : the first guess
Structured English:
- Find the derivative's coefficients, df.
- Repeat 8 times:
- Replace x with the x-intercept of the tangent at (x, f(x)): x − f(x) ÷ f′(x).
- Print x.
| Pseudocode | Python |
|---|---|
// poly(coeffs, x): the value at x of the polynomial with these coeffs |
# poly(coeffs, x): the value at x of the polynomial with these coeffs |
define poly(coeffs, x) |
def poly(coeffs, x): |
value ← 0 |
value = 0 |
for each coeff in coeffs |
for coeff in coeffs: |
value ← value*x + coeff |
value = value * x + coeff |
end for |
|
return value |
return value |
end |
|
define derivative(coeffs) |
def derivative(coeffs): |
dcoeffs ← [] |
dcoeffs = [] |
n ← len(coeffs) - 1 |
n = len(coeffs) - 1 |
for i from 1 to len(coeffs)-1 |
for i in range(len(coeffs) - 1): |
append (n - i + 1)*coeffs[i] to dcoeffs |
dcoeffs.append((n - i) * coeffs[i]) |
end for |
|
return dcoeffs |
return dcoeffs |
end |
|
// f(x) = x³ + 0x² - 2x - 5 |
# f(x) = x³ + 0x² - 2x - 5 |
// f'(x) = 3x² + 0x - 2 |
# f'(x) = 3x² + 0x - 2 |
f ← [1, 0, -2, -5] |
f = [1, 0, -2, -5] |
df ← derivative(f) |
df = derivative(f) |
x ← 1 |
x = 1 |
for i from 1 to 8 |
for i in range(1, 9): |
x ← x - poly(f, x)/poly(df, x) |
x = x - poly(f, x) / poly(df, x) |
print x |
print(x) |
end for |
Newton's method for any cubic, with input (translation exercise)#
The same method for any cubic ax³ + bx² + cx + d, with the coefficients and the first guess typed in when the program runs. Here is the Python: write the pseudocode, then switch the Code pane to Python to compare.
Structured English:
- Define f(x) = ax³ + bx² + cx + d and its derivative f′(x) = 3ax² + 2bx + c.
- Read a, b, c, d and a first guess x.
- Repeat 6 times:
- Replace x with x − f(x) ÷ f′(x).
- Print x.
def f(x):
return a * x ** 3 + b * x ** 2 + c * x + d
def df(x):
return 3 * a * x ** 2 + 2 * b * x + c
# a, b, c, d: the cubic's coefficients; x: the first guess
# type each value in the Console's box and press Enter
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
d = float(input('d = '))
x = float(input('x = '))
for i in range(1, 7):
x = x - f(x) / df(x)
print(x)
Starter:
define f(x)
return ???
end
define df(x)
return ???
end
input a
input b
input c
input d
input x
for i from 1 to 6
x ← ???
print x
end for
How input works in the app: press Run, and the Console asks "Type a value for a in the box above and press Enter". Type 1 in the Console's box and press Enter; it asks for b, and so on. Each value runs the program again from the start with all the values so far. A value that is a number (3, -1.5, 2/3) is read as a number; anything else is kept as text and never run as code.
Test case: a = 1, b = 0, c = −2, d = −5 from x = 2 gives 2.1, 2.09457, 2.09455: correct to 6 figures after three steps, where false position needed eight.
Secant method (exercise)#
The secant method is Newton's method without the derivative: it uses the line through the last two guesses in place of the tangent.
Structured English:
- Start with two guesses, x0 and x1.
- Repeat 5 times:
- Take the next guess where the line through (x0, f(x0)) and (x1, f(x1)) crosses the x-axis: x2 = x1 − f(x1) × (x1 − x0) ÷ (f(x1) − f(x0)).
- Drop x0: x0 takes x1's value, then x1 takes x2's.
- Print x1.
Test case: for x² − 2 = 0 from x0 = 1 and x1 = 2, the guesses are 1.33333, 1.4, 1.41463, 1.41421 (√2 to 6 figures).
Starter:
define f(x)
return x² - 2
end
x0 ← 1
x1 ← 2
for k from 1 to 5
x2 ← ???
x0 ← ???
x1 ← ???
print x1
end for
Fixed-point iteration (sample)#
Not in the Examples menu: type it into the Code pane to run it.
Some equations can be written as x = g(x). Then putting a guess into g, and the answer back in again, can settle on the solution, like pressing cos over and over on a calculator. Here g(x) = cos(x) in radians: from x = 1 it settles on 0.739086 after 34 steps.
Inputs:
- g : the function, with the equation written as x = g(x)
- x : the first guess
- tol : how close two answers in a row must be
Structured English:
- Start a step count at 0.
- Repeat:
- Keep the old x.
- Replace x with g(x), and add 1 to the step count.
- Until the new x and the old x differ by less than tol.
- Print x and the step count.
When does it converge? Near the solution, each step multiplies the error by about g′(x). It settles when |g′(x)| < 1 there, and the smaller |g′(x)| is, the faster. For cos, |g′(0.739)| = sin(0.739) ≈ 0.67, so each step keeps about two thirds of the error, and the answers zigzag either side of the solution because g′ is negative. Try g(x) = (x + 2 ÷ x) ÷ 2 instead: it finds √2 in a few steps, because g′(√2) = 0.
| Pseudocode | Python |
|---|---|
from math import cos |
|
define g(x) |
def g(x): |
return cos(x) |
return cos(x) |
end |
|
// solve x = g(x): put each answer back in until it settles |
# solve x = g(x): put each answer back in until it settles |
// tol: how close two answers must be; n: the steps taken |
# tol: how close two answers must be; n: the steps taken |
tol ← 10⁻⁶ |
tol = 10 ** (-6) |
x ← 1 |
x = 1 |
n ← 0 |
n = 0 |
repeat |
while True: |
x_old ← x |
x_old = x |
x ← g(x) |
x = g(x) |
n ← n + 1 |
n = n + 1 |
until abs(x - x_old) < tol |
if abs(x - x_old) < tol: |
break |
|
print x |
print(x) |
print n |
print(n) |
Integration (quadrature)#
Each method here adds up the areas of thin strips to estimate a definite integral.
Left Riemann sum (sample)#
Doc ▸ Examples ▸ Numerical methods ▸ Left Riemann sum
A left Riemann sum splits the interval into n strips of width h and treats each strip as a rectangle whose height is the function's value at the strip's left edge. Here f(x) = eˣ on [0, 1], so the exact answer is e − 1 = 1.71828; ten rectangles give 1.6338, an underestimate because eˣ is increasing.
Inputs:
- f : the function
- a, b : the ends of the interval
- n : the number of strips
Structured English:
- Work out the strip width, h = (b − a) ÷ n, and start a total at 0.
- For each strip i from 0 to n − 1:
- Add the rectangle's area, f(a + i × h) × h, to the total.
- Print the total.
| Pseudocode | Python |
|---|---|
define f(x) |
def f(x): |
return e^x |
return e ** x |
end |
|
// n rectangles of width h, from a to b |
# n rectangles of width h, from a to b |
n ← 10 |
n = 10 |
a ← 0 |
a = 0 |
b ← 1 |
b = 1 |
h ← (b-a)/n |
h = (b - a) / n |
total ← 0 |
total = 0 |
for i from 0 to n-1 |
for i in range(0, n): |
total ← total + f(a + i*h)*h |
total = total + f(a + i * h) * h |
end for |
|
print total |
print(total) |
Right and midpoint sums (exercise)#
Changing which point sets each rectangle's height changes the estimate.
Structured English:
- As for the left sum, but for strip i the height is:
- for a right sum, f(a + (i + 1) × h), at the strip's right edge;
- for a midpoint sum, f(a + (i + 0.5) × h), at its middle.
Test case: for ∫₁⁵ (x² − x) dx with 4 strips, the left sum is 20, the right sum is 40 and the midpoint sum is 29. The exact value is 29⅓.
Hint: start from the Left Riemann sum sample and change one line.
Trapezium rule (exercise)#
The trapezium rule joins the ends of each strip with a straight line, so each strip is a trapezium rather than a rectangle. It is the average of the left and right sums.
Structured English:
- Work out h = (b − a) ÷ n, and start the area at 0.
- For each strip k from 0 to n − 1:
- Let x be the strip's left edge, a + k × h.
- Add the trapezium's area, h × (f(x) + f(x + h)) ÷ 2.
- Print the area.
Test case: ∫₁⁵ (x² − x) dx with 4 strips gives 30 (exact 29⅓).
Starter:
define f(x)
return x² - x
end
a ← 1
b ← 5
n ← 4
h ← (b - a)/n
area ← 0
for k from 0 to n - 1
x ← ???
area ← area + ???
end for
print area
Monte Carlo area (translation exercise)#
A Monte Carlo method estimates an area by random sampling. The quarter of the unit circle in the first quadrant sits inside the unit square, so the fraction of random points in the square that land inside the circle estimates its area, π ÷ 4 ≈ 0.785. Here is the Python: write the pseudocode, then switch the Code pane to Python to compare.
Structured English:
- Start a count of hits at 0.
- Repeat n times:
- Pick a random point (x, y), with x and y each between 0 and 1.
- If x² + y² ≤ 1, the point is inside the quarter circle: add 1 to the hits.
- The area is about hits ÷ n; print it, and 4 × it as an estimate of π.
from random import random, seed
seed(1)
# n random points in the unit square; hits: those inside the quarter circle
n = 200
hits = 0
for i in range(1, n + 1):
x = random()
y = random()
if x ** 2 + y ** 2 <= 1:
hits = hits + 1
# the square's area is 1, so the quarter circle's is about hits/n
area = hits / n
print(area)
print(4 * area)
Starter:
seed(1)
n ← 200
hits ← 0
for i from 1 to n
x ← rand()
y ← ???
if ??? then
hits ← ???
end if
end for
area ← hits/n
print area
print 4×area
Test case: with seed(1) and 200 points the app gives an area of 0.795 and π ≈ 3.18. (Python's own random numbers differ, so its answer will be close but not the same.) Quadrupling the number of points roughly halves the typical error: far slower than the Riemann sums, but it works the same way for shapes that are hard to integrate.
Other numerical methods#
Derivatives from differences (exercise)#
A derivative is a limit of gradients of chords. A computer can use a small h in place of the limit.
Structured English:
- The forward difference is (f(x + h) − f(x)) ÷ h: the gradient of the chord to the right of x.
- The central difference is (f(x + h) − f(x − h)) ÷ (2h): the gradient of a chord either side of x, and usually much closer.
Test case: for f(x) = x³ at x = 2 with h = 0.1, the forward difference is 12.61 and the central difference is 12.01. The derivative is 12.
Hint: a one-line function such as f(x) ← x³ keeps the program short.
Euler's method (exercise)#
Euler's method solves a differential equation dx/dt = f(x, t) step by step, following the slope at each point for a short time.
Inputs:
- f : the rate, dx/dt = f(x, t)
- t, x : the starting point
- dt : the step size
Structured English:
- Repeat for the number of steps:
- Move x along the slope: add dt × f(x, t).
- Add dt to t.
- Print t and x.
Test case: for dx/dt = x − t with x = 0.5 when t = 0 and dt = 0.5, four steps give (0.5, 0.75), (1, 0.875), (1.5, 0.8125), (2, 0.46875). Smaller steps come closer to the exact solution, x = t + 1 − 0.5eᵗ.
Starter:
define f(x, t)
return x - t
end
t ← 0
x ← 0.5
dt ← 0.5
for k from 1 to 4
x ← ???
t ← ???
print t, x
end for
Arc length of a curve (exercise)#
The length of a curve given by x(t) and y(t) is the integral of √(x′(t)² + y′(t)²). A program can add up many short pieces.
Structured English:
- Split the t interval into n steps of size dt, and start the length at 0.
- Start t in the middle of the first step, t0 + dt ÷ 2.
- Repeat n times:
- Add √(x′(t)² + y′(t)²) × dt to the length.
- Move t on by dt.
- Print the length.
Test case: for x = t, y = t² from t = −1 to 2 (so x′ = 1 and y′ = 2t), 5 steps give 6.06906 and 50 steps give 6.12517. The exact length is 6.1257 to 4 decimal places.
Hint: a repeat n times loop.
Finance (recurrence relations)#
A recurrence relation works out each value from the one before it, which is exactly what a loop does: one pass of the loop is one step of the recurrence.
Compound interest (sample)#
Not in the Examples menu: type it into the Code pane to run it.
Compound interest adds the interest to the balance each period, so the next period earns interest on the interest too. As a recurrence, V₀ = 5000 and Vₙ₊₁ = R × Vₙ, where R = 1 + r and r is the interest rate per period. At 4.8% a year compounding monthly, r = 0.048 ÷ 12 = 0.004; after 3 years the balance is $5772.76, the same as 5000 × 1.004³⁶.
Inputs:
- v : the starting balance
- r : the interest rate per month
Structured English:
- For each month from 1 to 36:
- Multiply the balance by 1 + r.
- If it is the end of a year (the month is a multiple of 12):
- Print the year and the balance, to the cent.
| Pseudocode | Python |
|---|---|
// $5000 invested at 4.8% p.a., compounding monthly, for 3 years |
# $5000 invested at 4.8% p.a., compounding monthly, for 3 years |
// v: the balance; r: the interest rate per month |
# v: the balance; r: the interest rate per month |
v ← 5000 |
v = 5000 |
r ← 4.8/100/12 |
r = 4.8 / 100 / 12 |
for month from 1 to 36 |
for month in range(1, 37): |
v ← v × (1 + r) |
v = v * (1 + r) |
if month mod 12 = 0 then |
if month % 12 == 0: |
print month div 12, round(v, 2) |
print(month // 12, round(v, 2)) |
end if |
|
end for |
Depreciation (exercise)#
Depreciation is the loss of an asset's value over time. Flat-rate depreciation takes the same amount off each year, a linear recurrence Vₙ₊₁ = Vₙ − 3000. Reducing-balance depreciation takes the same percentage off each year, a geometric recurrence Vₙ₊₁ = 0.85 × Vₙ.
Structured English:
- Start both values at $30 000, and print them for year 0.
- For each year from 1 to 6:
- Take $3000 off the flat-rate value.
- Take 15% off the reducing-balance value.
- Print the year and both values, to the dollar.
Test case: after 3 years the values are $21 000 (flat rate) and $18 424 (reducing balance); after 6 years, $12 000 and $11 314. The flat-rate value falls by the same amount every year; the reducing-balance value falls fast at first and then more slowly, and never reaches zero.
Starter:
flat ← 30000
reducing ← 30000
print 0, flat, reducing
for year from 1 to 6
flat ← ???
reducing ← ???
print year, flat, round(reducing)
end for
Lists: searching and sorting#
Linear search in a list (exercise)#
To find an item in a list that is not in order, you have to look at each item in turn.
Structured English:
- For each position i from 1 to the length of the list:
- If the item at position i is the one wanted, report i and stop.
- If the end is reached, report that it is not there.
Test case: in [4, 9, 7, 1, 7], 7 is first found at position 3; 5 is not found.
Hint: return i inside a function stops the search at once.
Binary search (exercise)#
In a sorted list there is a much faster way, the same idea as bisection: look at the middle, and keep only the half that can hold the item.
Structured English:
- The item could be anywhere from position lo = 1 to hi = the length of the list.
- While lo ≤ hi:
- Look at the middle position, mid = (lo + hi) div 2.
- If the item there is the one wanted, report mid and stop.
- If it is too small, the item must be above it: move lo to mid + 1.
- Otherwise it must be below: move hi to mid − 1.
- Report that it is not there.
Test case: in [2, 4, 6, 34, 78, 88, 92, 102], 78 is at position 5 and 79 is not found. A list of a million sorted items takes at most 20 looks.
Starter:
define binary_search(data, item)
lo ← 1
hi ← len(data)
while lo ≤ hi do
mid ← (lo + hi) div 2
if data[mid] = item then
return mid
else if data[mid] < item then
lo ← ???
else
hi ← ???
end if
end while
return 0
end
print binary_search([2, 4, 6, 34, 78, 88, 92, 102], 78)
Selection sort and bubble sort (exercise)#
Two simple ways to put a list in order.
Structured English, selection sort:
- For each position i from 1 to the length of the list:
- Find the smallest item from position i onwards.
- Swap it with the item at position i.
Structured English, bubble sort:
- Repeat:
- Walk along the list, and swap each pair of neighbours that is the wrong way round.
- Until a whole walk makes no swaps.
Test case: [5, 2, 9, 1, 7] sorts to [1, 2, 5, 7, 9]. Count the comparisons each method makes.
Hint: swap two items through a spare variable: t ← a[i], a[i] ← a[i + 1], a[i + 1] ← t. A function gets its own copy of a list, so a sorting function must return the sorted list.
Chance and simulation#
Two dice: the total (sample)#
Doc ▸ Examples ▸ Intro ▸ Linear
A program with no loops or decisions runs each line once, top to bottom. This one rolls two six-sided dice and adds them; each run gives a new total, from 2 to 12.
Structured English:
- Roll each die: pick a whole number from 1 to 6.
- Add them, and print the total.
| Pseudocode | Python |
|---|---|
from random import randint |
|
die1 ← randint(1, 6) |
die1 = randint(1, 6) |
die2 ← randint(1, 6) |
die2 = randint(1, 6) |
total ← die1 + die2 |
total = die1 + die2 |
print total |
print(total) |
Two dice: the larger (sample)#
Doc ▸ Examples ▸ Probability ▸ Two D6: larger
Simulation estimates a probability or an average by doing the experiment many times. Here the experiment is: roll two dice and keep the larger. seed(42) makes the "random" rolls the same each run, so results can be compared. The theoretical mean is 161 ÷ 36 ≈ 4.47; more trials come closer to it.
Inputs:
- trials : how many times to do the experiment
Structured English:
- Start the total and the total of squares at 0.
- Repeat
trialstimes:- Roll two dice.
- Let big be the larger.
- Add big to the total, and big² to the total of squares.
- The mean is the total ÷ trials; work out the standard deviation from the total of squares.
- Print the mean and the standard deviation.
| Pseudocode | Python |
|---|---|
from math import sqrt |
|
from random import randint, seed |
|
seed(42) |
seed(42) |
trials ← 20 |
trials = 20 |
// big: the larger die; total and total_sq: sums of big and of big² |
# big: the larger die; total and total_sq: sums of big and of big² |
total ← 0 |
total = 0 |
total_sq ← 0 |
total_sq = 0 |
for trial from 1 to trials |
for trial in range(1, trials + 1): |
die1 ← randint(1, 6) |
die1 = randint(1, 6) |
die2 ← randint(1, 6) |
die2 = randint(1, 6) |
if die1 > die2 then |
if die1 > die2: |
big ← die1 |
big = die1 |
else |
else: |
big ← die2 |
big = die2 |
end if |
|
total ← total + big |
total = total + big |
total_sq ← total_sq + big*big |
total_sq = total_sq + big * big |
end for |
|
mean ← total/trials |
mean = total / trials |
sd ← sqrt((total_sq - trials*mean*mean)/(trials - 1)) |
sd = sqrt((total_sq - trials * mean * mean) / (trials - 1)) |
print mean |
print(mean) |
print sd |
print(sd) |
The sample space of two four-sided dice (sample)#
Doc ▸ Examples ▸ Probability ▸ Two D4 sample space
Nested loops list every combination: the inner loop runs right through for each pass of the outer one. There are 4 × 4 = 16 outcomes.
Structured English:
- Start with an empty list of outcomes.
- For each value of the first die, 1 to 4:
- For each value of the second die, 1 to 4:
- Add the pair to the list.
- For each value of the second die, 1 to 4:
- Print the list.
| Pseudocode | Python |
|---|---|
outcomes ← [] |
outcomes = [] |
for first from 1 to 4 |
for first in range(1, 5): |
for second from 1 to 4 |
for second in range(1, 5): |
append [first, second] to outcomes |
outcomes.append([first, second]) |
end for |
|
end for |
|
print outcomes |
print(outcomes) |
Waiting for three heads in a row (exercise)#
How many coin tosses does it take, on average, to see three heads in a row? A simulation can estimate it.
Structured English:
- Repeat for each trial:
- Start counts of tosses and of heads in a row at 0.
- While the run of heads is less than 3:
- Toss a coin (a random 0 or 1) and add 1 to the tosses.
- If it is a head, add 1 to the run; if a tail, the run goes back to 0.
- Add this trial's tosses to a total.
- Print the average number of tosses, the total ÷ the number of trials.
Test case: the average is close to 14 (the exact long-run mean is 14). With seed(7) and 100 trials your answer is fixed, so a classmate with the same program gets the same number.
Starter:
seed(7)
trials ← 100
total ← 0
for t from 1 to trials
tosses ← 0
run ← 0
while run < 3 do
tosses ← tosses + 1
if randint(0, 1) = 1 then
run ← ???
else
run ← ???
end if
end while
total ← total + tosses
end for
print total/trials
A long simulation makes a long trace table: turn the trace off (Trace: None) to run it quickly.