---
title: Floating-point units
heading: Alignment, normalization, rounding and fused multiply-add in hardware
eyebrow: S3 · Lesson 11 · Floating-point units
xp: 50
---

::: hook
An integer adder is one carry chain. A floating-point adder is a small pipeline: compare the exponents, shift the smaller significand into alignment, add or subtract, find where the leading one landed, shift it back into place, and round, all while tracking the bits that fell off the end so the rounding is exactly what IEEE 754 prescribes. That's why a floating-point add takes three to five cycles where an integer add takes one, and why every one of those steps is a hardware design problem.
:::

::: play
- The sawtooth is the spacing between adjacent floating-point numbers divided by the number itself, in units of the machine epsilon $2^{1-p}$, for a significand of p bits (24 for single, 53 for double, 11 for half).
- It stays between half an epsilon and one epsilon at every magnitude, $2^{-p}$ to $2^{1-p}$: each power of two starts a new binade with the same number of values. The bits set the size of the unit (see the readout); the shape never changes.
- That bounded relative spacing is what floating point buys; rounding to nearest makes each result's relative error at most $2^{-p}$.
:::

```sim plot
view: graph
x: x = 1..1000 log
y: r = 0..1.2
samples: 1200
slider: p = 11..53 step 1 = 24
plot: 2^(floor(log(x)/log(2)) - p + 1)/x/2^(1 - p) | label: spacing ÷ value, in units of ε
plot: 0.5 + 0*x | dashed | color: ch3 | label: unit roundoff ε/2
readout: machine epsilon ε = 2^(1 - p) | format: sci
readout: unit roundoff = 2^(-p) | format: sci
```

::: predict
## A floating-point adder adds 12 = 1.5 × 2³ and 1.25 = 1.25 × 2⁰. What does the alignment step do, and what significand and exponent come out?

- [x] Shift 1.25 right by 3 places to 0.15625; the sum 1.65625 × 2³ is already normalized
- [ ] Shift 1.5 left by 3 places; the sum is 13.25 × 2⁰
- [ ] Add the exponents to get 2³, then multiply the significands
- [ ] Shift both to exponent 0 and add as integers

::: reveal
The exponents differ by 3, so the smaller operand's significand is shifted right 3 places: $1.25/8 = 0.15625$. Adding gives $1.65625 \times 2^3 = 13.25$, already between 1 and 2, so no normalization shift is needed. Had the sum reached 2 or more, a one-place right shift and an exponent increment would fix it.
:::
:::

::: nameit
## The adder's steps

1. **Compare and swap:** subtract the exponents; the difference d is the alignment shift, and the larger operand goes on top.
2. **Align:** shift the smaller significand right by d with a barrel shifter, keeping three extra bits: **guard**, **round** and **sticky** (the OR of every bit shifted out below the round bit).
3. **Add or subtract** the significands.
4. **Normalize:** an addition can carry out (shift right one); a subtraction of close values can cancel many leading bits (shift left by the leading-zero count, which a **leading-zero anticipator** predicts in parallel with the subtraction).
5. **Round** to nearest, ties to even: round up if the bits below the kept significand exceed half an ULP, or equal half and the kept LSB is 1.

## Costs

- A barrel shifter for shifts up to S on n bits takes $\lceil\log_2(S + 1)\rceil$ levels of n multiplexers.
- A multiplier for p-bit significands forms $p^2$ partial-product bits (576 for single, 2809 for double).
- **Fused multiply-add** computes $ab + c$ with one rounding instead of two: more accurate, and the core of every dot product and matrix unit.

## Rounding error

With p significand bits, rounding to nearest has a relative error of at most $u = 2^{-p}$. A number in $[2^e, 2^{e+1})$ has an ULP of $2^{e - p + 1}$.
:::

::: example
## In single precision, what are 1 + 2⁻²⁴ and 1 + 1.5 × 2⁻²⁴?

::: solution
1. **Spacing near 1.** Single-precision numbers near 1 are spaced $2^{-23}$ apart.
2. **The first sum.** $1 + 2^{-24}$ sits exactly halfway between 1 and $1 + 2^{-23}$: guard 1, round and sticky 0, a tie. Since 1's last bit is 0, it rounds to **1.0**.
3. **The second sum.** $1 + 1.5 \times 2^{-24}$ is past halfway (guard and round both 1), so it rounds up:
   $$1 + 2^{-23} = 1.00000012$$

**Answer:** $1 + 2^{-24}$ rounds to 1.0, and $1 + 1.5 \times 2^{-24}$ rounds to $1 + 2^{-23} = 1.00000012$.
:::
:::

::: example
## Subtract 1.0 from the single-precision number nearest 1.0000001. How far must the result be normalized?

::: solution
1. **The stored number.** The nearest single to 1.0000001 is $1 + 2^{-23}$.
2. **Subtract.**
   $$(1 + 2^{-23}) - 1 = 2^{-23}$$
   exactly.
3. **Normalize.** The subtraction cancels 23 leading bits, so the normalizer shifts left 23 places and subtracts 23 from the exponent.
4. **What the result holds.** It is exact, but it carries only the one significant bit the inputs had: cancellation exposes earlier rounding.

**Answer:** the result, $2^{-23}$, must be shifted left 23 places.
:::
:::

::: example
## How large is a single-precision FMA's multiplier array, and how wide is the exact product it adds to c?

::: solution
1. **The array.** Two 24-bit significands make
   $$24^2 = 576$$
   partial-product bits, and a 48-bit exact product.
2. **The addition.** The FMA aligns c against all 48 bits before one final rounding, so its adder and shifter are about three times as wide as a plain adder's. That is part of why an FMA takes 4 or more cycles.

**Answer:** a 576-bit partial-product array, and a 48-bit exact product.
:::
:::

::: check
kind: parts
given: s = 1.25 | 1.5 | 1.75; t = 1.25 | 1.5 | 1.875; p = 4 | 5; q = 0 | 2 | 4

## A floating-point adder adds {s} × 2^{p} and {t} × 2^{q}.

::: part
answer: p - q
tolerance: 0

### How far is the smaller significand shifted?

::: misses
- [any] The exponent difference.
:::
:::

::: part
answer: (s + t/2^(p - q))/(1 + step(s + t/2^(p - q) - 2))
tolerance: 0.5%

### What significand comes out after normalization?

::: misses
- [any] Align, add, then bring the result into [1, 2): a sum of 2 or more shifts right one place.
:::
:::

::: part
answer: p + step(s + t/2^(p - q) - 2)
tolerance: 0

### And what exponent?

::: misses
- [any] Increment it if normalization shifted right.
:::
:::
:::

::: check
kind: parts
given: n = 24 | 27 | 53 | 56

## A barrel shifter moves an {n}-bit significand right by any amount from 0 to {n}.

::: part
answer: ceil(log(n + 1)/log(2) - 1e-9)
tolerance: 0

### How many multiplexer levels does it need?

::: misses
- [any] $\lceil\log_2(S + 1)\rceil$.
:::
:::

::: part
answer: n*ceil(log(n + 1)/log(2) - 1e-9)
tolerance: 0

### How many 2-to-1 multiplexers?

::: misses
- [any] n per level.
:::
:::
:::

::: check
kind: parts
given: p = 11 | 24 | 53

## A floating-point format has a {p}-bit significand (hidden bit included).

::: part
answer: p^2
tolerance: 0

### How many partial-product bits does its multiplier form?

::: misses
- [any] $p^2$.
:::
:::

::: part
answer: 2^(-p)
tolerance: 0.5%

### What is its unit roundoff?

::: misses
- [2^(1 - p)] That's the spacing just above 1; rounding to nearest halves it.
- [any] $2^{-p}$.
:::
:::
:::

::: check
kind: choice

## Why does IEEE 754 round ties to even rather than always up?

- [ ] Even numbers are easier to store
- [x] Always rounding ties up biases long sums upward; ties to even rounds up and down equally often on average, so the bias cancels
- [ ] It makes the hardware smaller than truncation
- [ ] It guarantees exact results for ties

::: misses
- [1] Every significand pattern is stored the same way.
- [3] Truncation is the cheapest of all; ties to even needs the guard, round and sticky bits.
- [4] A tie can't be represented exactly in the shorter format: some rounding is unavoidable.
:::
:::

::: check
kind: match

## Match each part of a floating-point adder to its job.

- Guard bit :: the first bit below the kept significand
- Sticky bit :: the OR of every bit shifted out below the round bit
- Leading-zero anticipator :: predicts the normalization shift while the subtraction runs
- Barrel shifter :: aligns the smaller significand to the larger exponent
- [extra] carry-save adder tree

::: misses
- [any] Follow a number through align, add, normalize and round.
:::
:::

::: check
kind: derivation
vars: p = 8..64, e = -100..100

## A binary floating-point format has p significand bits; x lies in $[2^e, 2^{e+1})$.

::: step
answer: 2^(e - p + 1)

### What is the ULP at x?
:::

::: step
answer: 2^(e - p)

### What is the largest rounding error at x, rounding to nearest?
:::

::: step
answer: 2^(-p)

### What is that relative to the smallest x in the binade?
:::

::: right
Right. Half an ULP over the binade's smallest value is the unit roundoff, the format's worst relative error.
:::
:::

::: check
kind: python

## Write `fadd(a, b)`: add two positive, normal single-precision numbers given as 32-bit integer bit patterns, returning the bit pattern of the correctly rounded sum (round to nearest, ties to even). Keep guard, round and sticky bits during alignment.

```python starter
def fadd(a, b):
    return a
```

```python solution
def fadd(a, b):
    ea, ma = (a >> 23) & 255, (a & 0x7FFFFF) | 0x800000
    eb, mb = (b >> 23) & 255, (b & 0x7FFFFF) | 0x800000
    if (eb, mb) > (ea, ma):
        ea, ma, eb, mb = eb, mb, ea, ma
    d = ea - eb
    ma <<= 3
    mb <<= 3
    if d > 0:
        sticky = 1 if mb & ((1 << d) - 1) else 0
        mb = (mb >> d) | sticky
    s = ma + mb
    e = ea
    if s >= (1 << 27):
        s = (s >> 1) | (s & 1)
        e += 1
    low = s & 7
    s >>= 3
    if low > 4 or (low == 4 and (s & 1)):
        s += 1
        if s >= (1 << 24):
            s >>= 1
            e += 1
    return (e << 23) | (s & 0x7FFFFF)
```

```python tests
import struct, random
f2b = lambda x: struct.unpack('>I', struct.pack('>f', x))[0]
b2f = lambda b: struct.unpack('>f', struct.pack('>I', b))[0]
assert b2f(fadd(f2b(12.0), f2b(1.25))) == 13.25, "The predict: 13.25."
assert fadd(f2b(1.0), f2b(2.0 ** -24)) == f2b(1.0), "A tie rounds to even: 1.0."
assert b2f(fadd(f2b(1.0), f2b(1.5 * 2.0 ** -24))) == 1 + 2.0 ** -23, "Past halfway rounds up."
rng = random.Random(7)
for _ in range(3000):
    x = b2f(f2b(rng.uniform(1, 2) * 2.0 ** rng.randint(-10, 10)))
    y = b2f(f2b(x * rng.uniform(1e-6, 1)))
    assert fadd(f2b(x), f2b(y)) == f2b(x + y), "Must match correctly rounded addition bit for bit."
```

::: right
Right. Three extra bits are enough for correct rounding of an addition, however far the smaller operand was shifted: the sticky bit stands in for everything below.
:::
:::

::: explain
## Why does a floating-point addition take several cycles when an integer addition of the same width takes one?

::: model
An integer adder only adds. A floating-point adder must first compare the exponents and shift the smaller significand into alignment, which needs a subtractor and a barrel shifter before the addition can start. After adding, the result may have carried out or, when nearly equal numbers are subtracted, lost many leading bits, so it must find the leading one and shift again. Finally it must round, which may carry all the way up the significand and force one more adjustment. Each step is a full-width operation in series, so the path is several times longer than one carry chain, and designs pipeline it over three to five cycles.
:::
:::

::: practice
::: check
given: p = 5 | 8; q = 1 | 3
answer: p - q
tolerance: 0

## Alignment shift for exponents {p} and {q}?

::: misses
- [any] The difference.
:::
:::

::: check
given: n = 7 | 15 | 23 | 31 | 32 | 63 | 64
answer: ceil(log(n + 1)/log(2) - 1e-9)
tolerance: 0

## Levels in a barrel shifter for shifts 0 to {n}?

::: misses
- [any] $\lceil\log_2(n + 1)\rceil$.
:::
:::

::: check
given: p = 8 | 16 | 113
answer: 2^(-p)
tolerance: 0.5%

## Unit roundoff for a {p}-bit significand?

::: misses
- [any] $2^{-p}$.
:::
:::
:::
