---
title: Floating point on a processor
heading: Float registers, what software floating point costs without them, and where the rounding bites
eyebrow: C8 · Lesson 21 · Floating point on a processor
xp: 40
---

::: hook
Lesson 20 did arithmetic on fractions with integers and a fixed binary point. Most programs use floating point instead, the IEEE 754 format of the digital logic course: a sign, an exponent and a 24-bit significand in a 32-bit `float`. On a processor with a floating-point unit, RISC-V's F extension, a `fadd.s` takes a few cycles from a separate bank of 32 float registers. On a small microcontroller without one, the compiler calls a library routine that unpacks, aligns, adds, normalizes and rounds in integer instructions, and the same line of C costs fifty times as much. Either way the results are rounded, and the rounding produces answers that surprise people who expect real arithmetic.
:::

::: play
- The spacing between adjacent `float` values, one unit in the last place (ULP), against the number's size. It doubles at every power of two: a float carries about seven significant digits wherever it is.
- The dashed line is 1, the size of the smallest step an integer counter can take. Past $2^{24}$ = 16 777 216 the floats are further apart than 1, so adding 1 does nothing.
- Slide the value and read its ULP and how many floats lie between it and its double.
:::

```sim plot
view: graph
x: x = 1..1e9 log
y: u = 1e-7..1000 log
slider: v = 1..1e9 = 1000 log
plot: 2^(floor(log(x)/log(2)) - 23) | samples: 2000 | label: spacing of floats (ULP)
plot: 1 + 0*x | dashed | color: ch2 | label: 1
readout: ULP at the slider = 2^(floor(log(v)/log(2)) - 23)
readout: significant decimal digits = 24*log(2)
```

::: predict
## In C on any IEEE 754 machine, a `float` starts at 0 and has 0.1f added ten times. What does it hold?

- [ ] Exactly 1.0
- [x] 1.0000001
- [ ] 0.9999999
- [ ] 1.1

::: reveal
1.000 000 12. 0.1 isn't representable in binary; the nearest float is 0.100 000 001 5, and each addition rounds again. The errors happen not to cancel. This is why programs compare floats with a tolerance, and why money is counted in integer cents.
:::
:::

::: nameit
## Floating point in hardware

RISC-V's F extension adds 32 float registers `f0` to `f31` and instructions such as `flw`/`fsw` (load and store), `fadd.s`, `fmul.s`, `fdiv.s`, `fsqrt.s`, fused multiply-add `fmadd.s` (one rounding for $a \times b + c$), and conversions `fcvt.w.s` (float to integer) and `fcvt.s.w`. The D extension adds `double`. Typical latencies are a few cycles for add and multiply, ten to twenty or more for divide and square root.

## Floating point in software

Without an FPU, `a + b` on floats becomes a call to a routine such as `__addsf3`: extract the exponents, shift the smaller number's significand right to align, add or subtract, normalize, round to nearest even, and handle zero, infinity and NaN. That's tens of instructions on the common path, often 50 to 100 cycles, and multiplication and division cost more. On a microcontroller without an FPU, fixed point (lesson 20) is often ten times faster, which is why firmware that runs a control loop at tens of kilohertz uses it.

## Where rounding shows

- **Spacing:** the gap between neighbors near $x$ is $2^{\lfloor\log_2 x\rfloor - 23}$ for `float`, relative precision about $6 \times 10^{-8}$, roughly 7 decimal digits.
- **Integers:** every integer up to $2^{24}$ = 16 777 216 is exact; beyond, odd integers aren't representable. A `float` counter stops counting at $2^{24}$.
- **Absorption:** adding a small number to a large one can do nothing at all.
- **Cancellation:** subtracting nearly equal numbers leaves few correct digits.
- **Order matters:** addition isn't associative, so summing small terms first is more accurate. **Kahan summation** carries the lost low-order bits forward in a second variable.
:::

::: example
## Decode the float bit pattern 0x40490FDB.

::: solution
1. **Split the fields.** In binary: sign 0; exponent bits 1000 0000 = 128; significand bits 0x490FDB = 4 788 187.
2. **The exponent.**
   $$128 - 127 = 1$$
3. **The value.**
   $$\begin{aligned} x &= \left(1 + \frac{4\,788\,187}{2^{23}}\right) \times 2^1 \\ &= 1.570\,796\,37 \times 2 \\ &= 3.141\,592\,74 \end{aligned}$$
4. **Compare with π.** It's the float nearest π, which is 0.000 000 09 too large.
5. **Its neighbors.** They are $2^{1 - 23} = 2.4 \times 10^{-7}$ away.

**Answer:** 0x40490FDB is 3.141 592 74, the float nearest π.
:::
:::

::: example
## A microcontroller without an FPU runs a 1000-tap filter in `float` at 100 MHz. Each multiply-add costs 160 cycles in software. A version with an FPU takes 8 cycles per multiply-add. How many output samples per second can each produce?

::: solution
1. **In software.**
   $$1000 \times 160 = 160\,000\ \text{cycles}$$
   per sample, so 625 samples per second at 100 MHz.
2. **With the FPU.**
   $$1000 \times 8 = 8000\ \text{cycles}$$
   per sample, 12 500 per second, twenty times as many.
3. **Fixed point.** A fixed-point version with a single-cycle 32-bit multiplier and accumulator might take 2 to 3 cycles per tap, faster still, at the cost of managing the scaling by hand.

**Answer:** 625 samples per second in software and 12 500 with the FPU.
:::
:::

::: example
## Sum $1/k$ for $k$ = 1 to 100 000 in `float`, once forward and once backward, and compare with the exact 12.090 146.

::: solution
1. **Forward.** The running sum is already about 12 when the terms shrink to $10^{-5}$, and each addition rounds to a ULP of about $10^{-6}$, so many terms are partly lost.
2. **The forward result.** It is 12.090 851, wrong in the fifth significant figure.
3. **Backward.** The small terms accumulate among themselves first, and the result is 12.090 153, wrong in the seventh.
4. **Compare.** The numbers and the operations are the same, and the order alone gives a hundred times less error.
5. **Kahan summation.** It gets the correctly rounded float in either order.

**Answer:** forward gives 12.090 851 and backward 12.090 153, against the exact 12.090 146.
:::
:::

::: check
given: x = 3 | 100 | 1500 | 70000 | 3000000
answer: 2^(floor(log(x)/log(2)) - 23)
tolerance: 0.5%

## What is the spacing between adjacent single-precision floats near {x}?

::: right
Right. $2^{\lfloor\log_2 x\rfloor - 23}$ = {answer}.
:::

::: misses
- [2^(floor(log(x)/log(2)) - 52)] That's double precision; a float has 23 stored significand bits.
- [x*2^(-23)] The spacing jumps at powers of two; use $2^{\lfloor\log_2 x\rfloor}$, not x.
- [any] Not yet. One ULP is $2^{e - 23}$ where $2^e \le x < 2^{e + 1}$.
:::
:::

::: check
given: e = 1 | 3 | 5 | 10; m = 1048576 | 4194304 | 6291456
answer: (1 + m/2^23)*2^e

## A float has sign 0, stored exponent {e} + 127 and significand bits equal to {m}. What value does it hold?

::: right
Right. $(1 + m/2^{23}) \times 2^e$ = {answer}.
:::

::: misses
- [m/2^23*2^e] Include the hidden leading 1.
- [(1 + m/2^23)*2^(e + 127)] Subtract the bias: the true exponent is {e}.
- [any] Not yet. Multiply $1 + m/2^{23}$ by 2 to the true exponent.
:::
:::

::: check
given: N = 500 | 1000 | 4000; c = 80 | 120 | 200; f = 48 | 100 | 200
answer: f*1e6/(N*c)
tolerance: 0.5%

## A filter needs {N} multiply-adds per output sample. Without an FPU each costs {c} cycles. At {f} MHz, how many samples per second can it produce?

::: right
Right. $f/(Nc)$ = {answer}.
:::

::: misses
- [f*1e6/N] Each multiply-add costs {c} cycles.
- [any] Not yet. Cycles per sample: $Nc$.
:::
:::

::: check
given: b = 20 | 24 | 30 | 53
answer: 2^b
tolerance: 0.5%

## A float format has a {b}-bit significand (counting the hidden 1). What's the largest integer below which every integer is exactly representable?

::: right
Right. $2^{\given{b}}$ = {answer}; beyond it the spacing exceeds 1.
:::

::: misses
- [2^(b - 1)] The hidden bit counts: {b} bits cover integers up to $2^{\given{b}}$.
- [any] Not yet. Spacing reaches 2 at $2^{\given{b}}$.
:::
:::

::: check
kind: parts
given: a = 1e6 | 3e6 | 1e7; d = 0.01 | 0.05 | 0.2

## In `float`, a program computes $(a + d) - a$ with $a$ = {a} and $d$ = {d}.

::: part
answer: 2^(floor(log(a)/log(2)) - 23)
tolerance: 0.5%

### What is the spacing of floats near {a}?

::: misses
- [a*2^(-23)] Use the power of two at or below {a}.
- [any] Not yet. $2^{\lfloor\log_2 a\rfloor - 23}$.
:::
:::

::: part
answer: 2^(floor(log(a)/log(2)) - 23)*round(d/2^(floor(log(a)/log(2)) - 23))
tolerance: 0.5%

### What does the expression return? (Round $d$ to the nearest multiple of that spacing.)

::: misses
- [d] {d} isn't a multiple of the spacing; the sum $a + d$ rounds to the nearest float.
- [any] Not yet. $a + d$ rounds to the nearest float, so the difference is a whole number of ULPs.
:::
:::

::: right
Right. The small number survives only to the nearest multiple of the large number's ULP: absorption, and often it vanishes entirely.
:::
:::

::: check
kind: choice

## A firmware engineer counts milliseconds in a `float`, adding 1.0f each tick. After about 4.7 hours the count stops increasing. Why?

- [x] At 2²⁴ = 16 777 216 the spacing between floats reaches 2, so adding 1 rounds back to the same value
- [ ] The float overflowed to infinity
- [ ] The timer interrupt stopped
- [ ] Floating-point addition is too slow at that rate

::: right
Right. 16 777 216 ms is 4.66 hours. Beyond that, x + 1 rounds to x under round-to-nearest-even. A 32-bit integer counter would run for 49.7 days.
:::

::: misses
- [2] A float overflows only near $3.4 \times 10^{38}$.
- [3] The interrupt still runs; its additions just stop having an effect.
- [4] Speed has nothing to do with it; the result is exact rounding.
:::
:::

::: check
kind: python
given: n = 5000 | 10000 | 20000 | 30000 | 50000 | 100000

## Compare summation orders in single precision. Write `to_f32(x)` that rounds a Python float to the nearest float32 (use `struct`), and `fsum32(values)` that adds them one by one with a float32 accumulator. Also write `kahan32(values)`, Kahan's compensated sum with every operation rounded to float32. For the harmonic series $1/k$, $k$ = 1 to `n` ({n}), set `fwd`, `bwd` and `kahan` (forward order, backward order, Kahan forward), and `exact` from `math.fsum` in double.

```python starter
import math
def to_f32(x):
    return x
fwd = bwd = kahan = exact = math.fsum(1 / k for k in range(1, n + 1))
```

```python solution
import math, struct
def to_f32(x):
    return struct.unpack('f', struct.pack('f', x))[0]
def fsum32(values):
    s = 0.0
    for v in values:
        s = to_f32(s + to_f32(v))
    return s
def kahan32(values):
    s, c = 0.0, 0.0
    for v in values:
        y = to_f32(to_f32(v) - c)
        t = to_f32(s + y)
        c = to_f32(to_f32(t - s) - y)
        s = t
    return s
terms = [1 / k for k in range(1, n + 1)]
fwd = fsum32(terms)
bwd = fsum32(reversed(terms))
kahan = kahan32(terms)
exact = math.fsum(terms)
```

```python tests
import math, struct
f = lambda x: struct.unpack('f', struct.pack('f', x))[0]
assert to_f32(0.1) == f(0.1) and to_f32(1 / 3) == f(1 / 3), "to_f32 must round to the nearest float32."
ex = math.fsum(1 / k for k in range(1, n + 1))
assert abs(exact - ex) < 1e-12, "exact is the double-precision sum."
assert abs(kahan - f(ex)) <= abs(f(ex)) * 2 ** -23, "Kahan's sum should land within one ULP of the exact value rounded to float32."
assert abs(bwd - ex) < abs(fwd - ex), "Summing backward, small terms first, should beat forward."
```

::: right
Right. Adding the small terms first loses less, and Kahan's two extra operations per term recover nearly full precision in either order.
:::
:::

::: explain
## A control loop on a microcontroller without an FPU misses its deadlines after a developer changes its arithmetic from fixed point to `float` "for readability". Explain why, and when floating point would be the right choice anyway.

::: model
Without a floating-point unit, every float operation is a call to a software routine that unpacks the exponent and significand, aligns them, operates with integer instructions, normalizes and rounds. That costs tens to hundreds of cycles per operation against one or two for an integer multiply-add, so a loop that fit its time budget in fixed point can take ten or more times as long in float and miss its deadline. Floating point is the right choice when the processor has an FPU, where a float multiply-add takes a few cycles; when the values' range is too wide for one fixed scaling; or when the code runs rarely, where readability and freedom from overflow outweigh the cost.
:::
:::

::: practice

::: check
given: x = 6 | 900 | 50000
answer: 2^(floor(log(x)/log(2)) - 23)
tolerance: 0.5%

## What is one ULP of a float near {x}?

::: misses
- [x*2^(-23)] Use the power of two at or below {x}.
- [any] $2^{\lfloor\log_2 x\rfloor - 23}$.
:::
:::

::: check
given: N = 64 | 256; c = 60 | 100; f = 16 | 72
answer: N*c/(f*1e6)*1e6
unit: µs
tolerance: 0.5%

## How long do {N} software float operations of {c} cycles take at {f} MHz, in µs?

::: misses
- [N/(f*1e6)*1e6] Multiply by the {c} cycles each.
- [any] $Nc/f$.
:::
:::
:::
