---
title: Recursion, bisection and binary search
heading: Halve the problem, then halve it again
eyebrow: A4 · Lesson 23 · Recursion, bisection and binary search
xp: 40
---

::: hook
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?

- [ ] 1,000,000
- [ ] 1000
- [x] 20
- [ ] 6

::: reveal
About 20, since $2^{20} \approx 10^6$. 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 $n$ and one whose time grows with $\log_2 n$, which lesson 24 is about.
:::
:::

::: nameit
## 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`.
:::

::: example
## Find $\sqrt[3]{2}$ by bisection.

::: solution
1. **Bracket the root.** $f(x) = x^3 - 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...
```

3. **Count the halvings.** From an interval of width 1 down to $10^{-12}$ takes 40 halvings, since $2^{40} \approx 10^{12}$.

**Answer:** $\sqrt[3]{2} = 1.259921$, found in 40 halvings.
:::
:::

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

::: 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...
```

2. **One stage.** It is 1 kΩ in series with 1 kΩ ∥ 1 kΩ, which is 1.5 kΩ.
3. **Many stages.** As the ladder grows, the value settles at the golden ratio times 1 kΩ:
   $$\begin{aligned} R &= 1000 \times \frac{1 + \sqrt5}{2} \\ &= 1618\ \Omega \end{aligned}$$

**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
kind: python
given: n = 1..8 int; R = 100 | 1000 | 4700

## 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` = {n} and `R` = {R}.

```python starter
def parallel(a, b):
    return a * b / (a + b)

def ladder(n, R):
    return R

Req = ladder(n, R)
print(Req)
```

```python solution
def parallel(a, b):
    return a * b / (a + b)

def ladder(n, R):
    if n == 0:
        return R
    return R + parallel(R, ladder(n - 1, R))

Req = ladder(n, R)
print(Req)
```

```python tests
import math
assert math.isclose(ladder(0, 1000), 1000), "ladder(0, R) is just R."
assert math.isclose(ladder(1, 1000), 1500), "ladder(1, 1000) should be 1000 + (1000 ∥ 1000) = 1500."
assert math.isclose(ladder(2, 1000), 1600), "ladder(2, 1000) should be 1000 + (1000 ∥ 1500) = 1600."
```

::: right
Right. The function's structure matches the circuit's: each stage wraps the ladder behind it.
:::
:::

::: check
kind: python
given: c = 2 | 3 | 5 | 10

## Write `bisect(f, a, b, tol=1e-12)` and use it to set `r` to the root of $x^3 - c$ between 0 and `c` (`c` = {c}).

```python starter
def bisect(f, a, b, tol=1e-12):
    return (a + b) / 2

r = bisect(lambda x: x**3 - c, 0, c)
print(r)
```

```python solution
def bisect(f, a, b, tol=1e-12):
    fa = f(a)
    while b - a > tol:
        m = (a + b) / 2
        fm = f(m)
        if (fm < 0) == (fa < 0):
            a, fa = m, fm
        else:
            b = m
    return (a + b) / 2

r = bisect(lambda x: x**3 - c, 0, c)
print(r)
```

```python tests
assert abs(bisect(lambda x: x**2 - 2, 0, 2) - 2**0.5) < 1e-9, "bisect(lambda x: x**2 - 2, 0, 2) should find √2. Keep the half where the sign changes, until the interval is narrower than tol."
assert abs(r - c ** (1 / 3)) < 1e-9, "r should be the cube root of c."
```

::: right
Right. Once the root is bracketed, bisection can't miss it.
:::
:::

::: check
kind: python
given: target = 15 | 100 | 3300 | 47000 | 90000

## 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 starter
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
xs = [m * 10**d for d in range(1, 5) for m in E12]

def first_at_least(xs, target):
    return 0

i = first_at_least(xs, target)
v = xs[i] if i < len(xs) else None
print(i, v)
```

```python solution
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
xs = [m * 10**d for d in range(1, 5) for m in E12]

def first_at_least(xs, target):
    lo, hi = 0, len(xs)
    while lo < hi:
        mid = (lo + hi) // 2
        if xs[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

i = first_at_least(xs, target)
v = xs[i] if i < len(xs) else None
print(i, v)
```

```python tests
import bisect
assert first_at_least([1, 3, 5, 7], 4) == 2, "first_at_least([1, 3, 5, 7], 4) should be 2, the index of 5."
assert first_at_least([1, 3, 5, 7], 5) == 2, "An exact match counts: the first value at or above 5 is 5 itself."
assert first_at_least([1, 3, 5, 7], 9) == 4, "With nothing at or above the target, return len(xs)."
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
xs2 = [m * 10**d for d in range(1, 5) for m in E12]
j = bisect.bisect_left(xs2, target)
assert v == (xs2[j] if j < len(xs2) else None), "v should be the first E12 value at or above the target."
```

::: right
Right. The invariant "the answer is in [lo, hi]" keeps the loop correct; it ends when the range is one point.
:::
:::

::: check
kind: python
given: k = 0..3 int

## 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 starter
lists = [[1000, 1000], [1000, 2200, 4700], [100, 220, 330, 470, 680], [10e3] * 6]
rs = lists[k]

def parallel_all(rs):
    return sum(rs)

Req = parallel_all(rs)
print(Req)
```

```python solution
lists = [[1000, 1000], [1000, 2200, 4700], [100, 220, 330, 470, 680], [10e3] * 6]
rs = lists[k]

def parallel_all(rs):
    if len(rs) == 1:
        return rs[0]
    rest = parallel_all(rs[1:])
    return rs[0] * rest / (rs[0] + rest)

Req = parallel_all(rs)
print(Req)
```

```python tests
want = 1 / sum(1 / r for r in rs)
assert abs(Req - want) < 1e-9 * want, f"Req should be {want:.6g} Ω, the same as 1/sum(1/R)."
assert parallel_all([470]) == 470, "One resistor on its own is just itself: that's the base case."
```

::: right
Right. Each call strips off one resistor and hands the rest to itself, until one is left. The answer matches $1/\sum(1/R)$, which is the non-recursive way to say the same thing.
:::
:::

::: check
kind: python
given: Rm = 2000 | 5000 | 20000 | 50000

## A thermistor has $R(T) = R_0 e^{B(1/T - 1/T_0)}$ with $R_0$ = 10 kΩ at $T_0$ = 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` = {Rm} Ω, and `steps` to how many halvings that took.

```python starter
import math
def R(T):
    return 10e3 * math.exp(3950 * (1 / T - 1 / 298.15))
a, b = 250.0, 400.0
T, steps = (a + b) / 2, 0
print(T, steps)
```

```python solution
import math
def R(T):
    return 10e3 * math.exp(3950 * (1 / T - 1 / 298.15))
a, b = 250.0, 400.0
steps = 0
while b - a > 1e-6:
    m = (a + b) / 2
    if R(m) > Rm:
        a = m
    else:
        b = m
    steps += 1
T = (a + b) / 2
print(T, steps)
```

```python tests
import math
exact = 1 / (1 / 298.15 + math.log(Rm / 10e3) / 3950)
assert abs(T - exact) < 1e-6, f"T should be {exact:.6f} K. R falls as T rises, so if R(m) is above Rm the root is above m."
assert 27 <= steps <= 29, f"Halving 150 K down to 1e-6 K takes 28 steps, not {steps}."
```

::: right
Right. The resistance falls as the temperature rises, so a reading above `Rm` means the answer is hotter. 150 K narrowed to a microkelvin is $\log_2(1.5 \times 10^8)$, about 28 halvings, whatever the reading.
:::
:::

::: check
given: w = 3 | 4 | 8 | 10; e = 3 | 6 | 9
answer: ceil(log(w*10^e)/log(2))
tolerance: 0.1

## Bisection starts on an interval {w} wide and stops once the interval is narrower than $10^{-\given{e}}$. How many halvings does that take?

::: right
Right. After $n$ halvings the interval is $\given{w}/2^n$, so you need $2^n > \given{w} \times 10^{\given{e}}$: {answer} halvings.
:::

::: misses
- [ceil(log(w*10^e)/log(2)) - 1] One short: after that many halvings the interval is still wider than $10^{-\given{e}}$. Round up.
- [ceil(log(10^e)/log(2))] That's the count for an interval 1 wide. Start from the width, {w}.
- [w*10^e] That's how many steps a search one step at a time would need. Each halving divides the interval by 2.
- [any] Not yet. Find the smallest $n$ with $\given{w}/2^n < 10^{-\given{e}}$.
:::
:::

::: explain
## Why does every recursive function need a base case?

::: model
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

::: check
kind: python
given: n = 3..12 int

## Write a recursive `power2(n)` returning $2^n$ (with `power2(0) = 1`). Set `p = power2(n)`.

```python starter
def power2(n):
    return 2 * n

p = power2(n)
print(p)
```

```python solution
def power2(n):
    if n == 0:
        return 1
    return 2 * power2(n - 1)

p = power2(n)
print(p)
```

```python tests
assert power2(0) == 1 and power2(5) == 32, "power2(0) should be 1 and power2(5) should be 32."
assert p == 2**n, "p should be 2**n."
```
:::

::: check
kind: python
given: a = 2 | 5 | 7

## Use bisection on $[1, a]$ to set `r` to $\sqrt{a}$ (`a` = {a}), to within $10^{-10}$.

```python starter
r = 0
print(r)
```

```python solution
lo, hi = 1.0, float(a)
while hi - lo > 1e-12:
    m = (lo + hi) / 2
    if m * m < a:
        lo = m
    else:
        hi = m
r = (lo + hi) / 2
print(r)
```

```python tests
assert abs(r - a ** 0.5) < 1e-10, "r should be √a to within 1e-10."
```
:::
:::
