---
title: Arithmetic lab
heading: Prefix adders, Booth recoding, Dadda trees and Newton–Raphson, bit-exact in Python
eyebrow: S3 · Lesson 15 · Arithmetic lab
xp: 60
---

::: hook
Arithmetic hardware is easiest to trust when it has been modeled bit for bit and compared against plain integer arithmetic on thousands of inputs. This lab builds the models that hardware designers keep beside their RTL: a Kogge–Stone adder that counts its own levels, a radix-4 Booth recoder, a Dadda-tree stage counter, and a Newton–Raphson reciprocal whose correct bits double each step. Each one checks a formula from lessons 8 to 11 against the thing itself.
:::

::: play
- The stems are the correct bits of a Newton–Raphson reciprocal after k iterations, starting from a seed accurate to the slider's number of bits.
- Each iteration squares the error, so the correct bits double: an 8-bit table seed reaches 64 bits in three steps.
- The dashed line marks the 53 bits of a double's significand.
:::

```sim plot
view: graph
x: k = 0..5
y: b = 0..140
samples: 6
slider: s = 2..16 step 1 = 8
plot: s*2^k | stems | label: correct bits
plot: 53 + 0*k | dashed | label: double precision
```

::: predict
## Radix-4 Booth recoding turns each pair of multiplier bits, with the bit below them, into a digit $-2y_{2i+1} + y_{2i} + y_{2i-1}$. What digits does the 8-bit multiplier 0x5D (93) give, least significant first?

- [x] 1, −1, 2, 1
- [ ] 1, 3, 1, 1
- [ ] 2, −1, 1, 1
- [ ] 1, 1, 1, 0, 1, 0, 1, 0

::: reveal
0x5D is 01011101. With $y_{-1} = 0$: digit 0 is $0 + 1 + 0 = 1$; digit 1 is $-2 + 1 + 0 = -1$; digit 2 is $0 + 1 + 1 = 2$; digit 3 is $0 + 1 + 0 = 1$. Check: $1 - 4 + 2 \times 16 + 64 = 93$. Four digits for eight bits: half the partial products, each an easy multiple of the multiplicand.
:::
:::

::: nameit
## What the lab builds

- **Kogge–Stone:** bitwise $g_i = a_ib_i$, $p_i = a_i \oplus b_i$; then $\log_2N$ levels of the prefix operator $(G, P) \circ (G', P') = (G + PG', PP')$ at spans 1, 2, 4, …; the carry into bit i is the group generate $G_{i-1:0}$, and $s_i = p_i \oplus c_i$.
- **Booth radix 4:** digits $d_i = -2y_{2i+1} + y_{2i} + y_{2i-1}$ with $y = \sum d_i4^i$ for two's complement y.
- **Dadda:** the heights 2, 3, 4, 6, 9, 13, 19, … (each $\lfloor1.5\times\rfloor$ the last); h rows need as many stages as there are heights below h.
- **Newton–Raphson:** $x_{k+1} = x_k(2 - dx_k)$, with $1 - dx_{k+1} = (1 - dx_k)^2$.
:::

::: check
kind: python

## Write `ks_add(a, b, n)`: add two n-bit unsigned numbers (n a power of two) with a Kogge–Stone prefix network, returning (sum mod $2^n$, number of prefix levels). Build it from g, p and the prefix operator; don't use `a + b`.

```python starter
def ks_add(a, b, n):
    return (0, 0)
```

```python solution
def ks_add(a, b, n):
    g = [((a >> i) & (b >> i)) & 1 for i in range(n)]
    p = [((a >> i) ^ (b >> i)) & 1 for i in range(n)]
    G, P = g[:], p[:]
    d, levels = 1, 0
    while d < n:
        NG, NP = G[:], P[:]
        for i in range(d, n):
            NG[i] = G[i] | (P[i] & G[i - d])
            NP[i] = P[i] & P[i - d]
        G, P = NG, NP
        d *= 2
        levels += 1
    s = 0
    for i in range(n):
        c = G[i - 1] if i > 0 else 0
        s |= (p[i] ^ c) << i
    return (s, levels)
```

```python tests
import random
r = random.Random(3)
for _ in range(2000):
    x, y = r.getrandbits(16), r.getrandbits(16)
    assert ks_add(x, y, 16)[0] == (x + y) & 0xFFFF, "Must match integer addition."
assert ks_add(0xFFFF, 1, 16) == (0, 4), "The longest carry: 16 bits in 4 levels."
assert ks_add(5, 7, 64)[1] == 6, "64 bits: 6 levels."
```

::: right
Right. The carry into every bit is ready after $\log_2N$ levels, however far it has to travel.
:::
:::

::: check
kind: python

## Write `booth4(y, n)`: the radix-4 Booth digits of the n-bit two's complement number y (n even), least significant first.

```python starter
def booth4(y, n):
    return []
```

```python solution
def booth4(y, n):
    y &= (1 << n) - 1
    digits, prev = [], 0
    for i in range(0, n, 2):
        b0 = (y >> i) & 1
        b1 = (y >> (i + 1)) & 1
        digits.append(-2 * b1 + b0 + prev)
        prev = b1
    return digits
```

```python tests
val = lambda d: sum(x * 4 ** i for i, x in enumerate(d))
assert booth4(0x5D, 8) == [1, -1, 2, 1], "The predict: 1, −1, 2, 1."
assert all(val(booth4(y, 8)) == (y if y < 128 else y - 256) for y in range(256)), "Every 8-bit value, negatives included."
assert all(-2 <= d <= 2 for y in range(256) for d in booth4(y, 8)), "Digits stay within ±2."
assert len(booth4(12345, 16)) == 8, "16 bits make 8 partial products."
```

::: right
Right. Negative numbers come out with no special case: the top digit carries the sign.
:::
:::

::: check
kind: python

## Write `dadda_stages(h)`: the number of reduction stages a Dadda tree needs to bring h rows down to 2.

```python starter
def dadda_stages(h):
    return 0
```

```python solution
def dadda_stages(h):
    seq = [2]
    while seq[-1] < h:
        seq.append(seq[-1] * 3 // 2)
    return sum(1 for d in seq if d < h)
```

```python tests
assert [dadda_stages(h) for h in (3, 4, 8, 9, 10, 16, 32, 64)] == [1, 2, 4, 4, 5, 6, 8, 10], "Heights 2, 3, 4, 6, 9, 13, 19, 28, 42, 63."
assert dadda_stages(2) == 0, "Two rows need no reduction."
```

::: right
Right. A 32 × 32 multiplier needs 8 stages for its 32 rows, and Booth recoding's 17 rows need 6.
:::
:::

::: check
kind: python

## Write `nr_bits(d, x0, k)`: run k Newton–Raphson steps for 1/d from x0 and return the number of correct bits, $-\log_2|1 - dx_k|$. Then check that the bits double.

```python starter
import math

def nr_bits(d, x0, k):
    return 0.0
```

```python solution
import math

def nr_bits(d, x0, k):
    x = x0
    for _ in range(k):
        x = x * (2 - d * x)
    return -math.log2(abs(1 - d * x))
```

```python tests
b = [nr_bits(0.75, 1.3, k) for k in range(3)]
assert abs(b[0] - 5.32) < 0.01, "The seed: 5.3 bits."
assert abs(b[1] - 2 * b[0]) < 1e-6 and abs(b[2] - 4 * b[0]) < 1e-6, "Each step doubles the bits."
```

::: right
Right. Quadratic convergence is why a small table and two or three multiplies beat a long division.
:::
:::

::: explain
## Why is radix-4 Booth recoding worth its extra logic in a multiplier?

::: model
A plain multiplier makes one partial product per multiplier bit, so a 32-bit multiply sums 32 rows, and the reduction tree's size and depth grow with the number of rows. Booth recoding reads the multiplier two bits at a time, with one bit of overlap, and turns each pair into a digit from −2 to 2. Every digit's partial product is easy to form: zero, the multiplicand, twice it by a shift, or their negations. That halves the rows to about 17, saving roughly half the adders in the tree and two of its stages, and it handles two's complement operands without correction terms. The recoder and the multiplexers it drives are small compared with the adders they remove.
:::
:::
