A423 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

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?

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 n stages is a series resistor followed by a shunt resistor in parallel with a ladder of n−1 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 a and b, 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 23 by bisection.

Show the solution
  1. Bracket the root. f(x)=x3−2 is −1 at x=1 and +6 at x=2, so the root is between them.
  2. Bisect.
r = bisect(lambda x: x**3 - 2, 1, 2)
print(r)        # 1.2599210498951...
  1. Count the halvings. From an interval of width 1 down to 10−12 takes 40 halvings, since 240≈1012.

Answer 23=1.259921, found in 40 halvings.

Worked example

Find the resistance of a ladder with 1, 2 and 10 stages of 1 kΩ.

Show the solution
  1. Define parallel and call the recursive ladder.
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...
  1. One stage. It is 1 kΩ in series with 1 kΩ ∥ 1 kΩ, which is 1.5 kΩ.
  2. Many stages. As the ladder grows, the value settles at the golden ratio times 1 kΩ: R=1000×1+52=1618Ω

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 x3−c 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 R(T)=R0eB(1/T−1/T0) with R0 = 10 kΩ at T0 = 298.15 K and B = 3950 K. Using bisection between 250 K and 400 K, set T to the temperature (in kelvins, within 10−6 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 10−3. How many halvings does that take?

Explain why

Why does every recursive function need a base case?

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.