A4 · Lesson 23 · Recursion, bisection and binary search
Halve the problem, then halve it again
To find the resistor value that gives a 1 kHz corner, you could try every value in order. Or you could try the middle of the range, see which half the answer is in, and repeat. Twenty halvings narrow a range by a factor of a million. Halving shows up everywhere: bisection finds roots of equations, binary search finds values in sorted tables, and a successive-approximation ADC finds a voltage one bit at a time the same way. Many of these are naturally written as functions that call themselves: recursion.
Predict
A sorted list holds 1,000,000 values. About how many halvings does binary search need to find any one of them?
About 20, since . Each comparison halves the part of the list that can still hold the answer. That's the difference between an algorithm whose time grows with and one whose time grows with , which lesson 24 is about.
Name it
Recursion
A recursive function calls itself on a smaller version of the problem, with a base case that stops it:
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # smaller problem
Recursion fits problems that are defined in terms of themselves. A resistor ladder is one: a ladder of stages is a series resistor followed by a shunt resistor in parallel with a ladder of stages.
def ladder(n, R):
if n == 0:
return R # the terminating resistor
return R + parallel(R, ladder(n - 1, R))
Every recursive function needs a base case it's sure to reach, or it recurses forever (Python stops it at about 1000 levels).
Bisection: roots by halving
If a continuous function changes sign between and , it has a root between them. Check the middle: whichever half still has the sign change keeps the root.
def bisect(f, a, b, tol=1e-12):
fa = f(a)
while b - a > tol:
m = (a + b) / 2
if (f(m) < 0) == (fa < 0):
a, fa = m, f(m) # root is in [m, b]
else:
b = m # root is in [a, m]
return (a + b) / 2
It's slow compared with Newton's method (lesson 37), about one bit of precision per step, but it can't fail once you've bracketed the root.
Binary search in a sorted list
The same halving finds where a value belongs in a sorted list:
def first_at_least(xs, target):
lo, hi = 0, len(xs) # the answer is in [lo, hi]
while lo < hi:
mid = (lo + hi) // 2
if xs[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
It returns the index of the first value at or above target (or len(xs) if there's none). Python's bisect module has a ready-made version, bisect.bisect_left.
Worked example
Find by bisection.
Show the solution
- Bracket the root. is −1 at and +6 at , so the root is between them.
- Bisect.
r = bisect(lambda x: x**3 - 2, 1, 2)
print(r) # 1.2599210498951...
- Count the halvings. From an interval of width 1 down to takes 40 halvings, since .
Answer , found in 40 halvings.
Worked example
Find the resistance of a ladder with 1, 2 and 10 stages of 1 kΩ.
Show the solution
- Define
paralleland call the recursiveladder.
def parallel(a, b):
return a * b / (a + b)
for n in (1, 2, 10):
print(n, ladder(n, 1000)) # 1500.0, 1600.0, 1618.03...
- One stage. It is 1 kΩ in series with 1 kΩ ∥ 1 kΩ, which is 1.5 kΩ.
- Many stages. As the ladder grows, the value settles at the golden ratio times 1 kΩ:
Answer 1.5 kΩ for one stage, 1.6 kΩ for two and 1618 Ω for ten, which is 1 kΩ times the golden ratio.
Check
Write the recursive ladder(n, R): R for n = 0, otherwise R in series with (R in parallel with ladder(n - 1, R)). Set Req = ladder(n, R) for n = 3 and R = 100.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write bisect(f, a, b, tol=1e-12) and use it to set r to the root of between 0 and c (c = 3).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write first_at_least(xs, target) by binary search, returning the index of the first value at or above target in a sorted list (or len(xs) if none). Use it on the starter's E12 list, and set v to the value found (or None if there isn't one).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write a recursive parallel_all(rs) returning the resistance of a list of resistors all in parallel: one resistor is itself, and otherwise it's the first resistor in parallel with parallel_all of the rest. Then set Req = parallel_all(rs) for the list the starter picks.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
A thermistor has with = 10 kΩ at = 298.15 K and = 3950 K. Using bisection between 250 K and 400 K, set T to the temperature (in kelvins, within K) where it reads Rm = 5000 Ω, and steps to how many halvings that took.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Bisection starts on an interval 4 wide and stops once the interval is narrower than . How many halvings does that take?
Explain why
Why does every recursive function need a base case?
A recursive function solves a problem by calling itself on a smaller version of it. Without a case that's answered directly, the calls would keep shrinking the problem forever and never return anything; Python would eventually stop with a recursion error. The base case is the smallest problem, solved without recursion, and every chain of calls has to reach it so the answers can be built back up.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.