69а. Fixed-point arithmetic: Q15 and Q31, rounding, saturation, division and accuracy against float
In section 69.9 fixed point is shown briefly: a scale, the Q15 format,
one multiplication with saturation. Here it is in detail and with numbers: how the
Qm.n format works and how to choose m and n, how to convert from float and back, why
addition is dangerous, how to multiply with rounding rather than truncation, what
the saturation instructions SSAT and QADD of Cortex-M3/M4 do and why gcc does not
insert them by itself, how to divide, how an FIR filter in Q15 and Q31 is built and how much
more or less accurate it is than the same filter in float. And the main question —
when all this is needed: on Cortex-M0 and M3 without an FPU every float operation is
a library call.
Basis: alg.c built with gcc 12.2.0 on the computer (stm-sys:1) and run by
host.c — boundary values, 100000 random multiplications against the exact
product, a 16-tap FIR filter on 2048 samples in Q15, Q31 and
float against a reference in double. The same alg.c built with
arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F, Cortex-M3 and
Cortex-M0: function sizes, library calls and the instructions chosen by the
compiler — from the disassembly; for M0 a program with the filter was built
completely to see the weight of the float library. There are no cycles here — nothing was
measured on silicon.
Terms used in the documentation
Original Meaning Qm.n format the Qm.n format: m bits of signed integer part, n bits of fraction fractional bits how many low bits are given to the fraction saturating arithmetic a result beyond the edge is replaced by the edge wrap-around a result beyond the edge appears from the other end round to nearest add half a step before the shift guard bits spare accumulator bits for the sum of many products SSAT, QADD Cortex-M3/M4 instructions: saturation to n bits and saturating addition soft-float software floating point: float operations as library calls signal-to-quantization-noise ratio the ratio of signal to quantization noise, in decibels In plain words. A fixed-point number is an integer about which it is agreed that it must be mentally divided by a power of two. In Q15 the number 16384 means 16384 / 32768 = 0.5. The processor adds and multiplies ordinary integers, and the programmer watches two things: where the point moved after a multiplication and whether the number went past the edge.
69а.1 The Qm.n format
The notation Qm.n means: the number has m bits of integer part (including the sign — by the convention adopted by ARM) and n bits of fraction. The value is the integer divided by 2ⁿ. The step is 2⁻ⁿ, the range is set by the remaining bits. The four formats met most often:
| Format | type | from | to | step |
|---|---|---|---|---|
| Q15 (Q1.15) | int16_t |
-1 | 0.99997 | 3.05e-05 |
| Q7.8 | int16_t |
-128 | 127.99609 | 0.00391 |
| Q31 (Q1.31) | int32_t |
-1 | 0.9999999995 | 4.66e-10 |
| Q16.16 | int32_t |
-32768 | 32767.99998 | 1.53e-05 |
Q15 and Q31 are the formats of digital signal processing: everything lies in the range from −1 to almost +1, and the product of two such numbers is also at most 1 in magnitude. This is the main convenience: multiplication does not leave the range (almost — about the exception below). Q7.8 and Q16.16 are for quantities with an integer part: degrees, revolutions, volts.
Choosing m and n is a choice between range and step at a given width.
Temperature from −40 to +125 °C with a 0.01 °C step: a range of ±128 is needed — seven
integer bits and a sign — and a step no coarser than 0.01 — seven fractional bits give
0.0078. In total 15 bits: Q8.7 in int16_t fits. An ADC signal
normalised to full scale is Q15. Filter coefficients that are all
less than 1 in magnitude are Q15 or Q31.
typedef int16_t q15_t; /* Q1.15: значение = n / 32768 */
typedef int32_t q31_t; /* Q1.31: значение = n / 2147483648 */
Why the top edge is 0.99997 rather than 1: int16_t has values from −32768 to
+32767, and +32768 is not among them. One is unrepresentable in Q15, while −1 is.
Hence all the pitfalls with "−1 × −1".
69а.2 Converting from float and back
Converting from float means multiplying by 2ⁿ, rounding and limiting:
q15_t q15_from_float(float x)
{
float s = x * 32768.0f;
s += (s >= 0.0f) ? 0.5f : -0.5f;
if (s >= 32767.0f)
return Q15_MAX;
if (s <= -32768.0f)
return Q15_MIN;
return (q15_t)s;
}
The cast (q15_t)s truncates the fraction towards zero, so half a step is
added beforehand with the sign of the number — this is rounding to nearest. Without
the limit 1.0f would give 32768, which does not fit in int16_t; with it
the run gave 32767, and −32768 for −1.0f. The number 0.3 became 9830, and
the reverse conversion 9830 / 32768 gave 0.2999878: the representation error is
less than half a step.
The reverse conversion is multiplication by 1/2ⁿ, not division: the constant 1/32768 is computed by the compiler at build time, and there is no division:
float q15_to_float(q15_t q)
{
return (float)q * (1.0f / 32768.0f);
}
There is a subtlety for Q31: float has only 24 significant bits, Q31 has 31. Converting
float → Q31 loses the low 7 bits, and a Q31 obtained from float is no more accurate than
the float itself. Besides, 2³¹ − 1 is unrepresentable in float: the nearest
smaller value is 2147483520, so the saturation limit is compared with
2147483648.0f.
In firmware conversion from float is done once — when computing
coefficients, when reading settings — not in the working loop: on M0 the
q15_from_float function itself calls five float library functions (multiplication,
addition, two comparisons and conversion to integer).
69а.3 Addition: wrap-around and saturation
Adding two Q15 numbers is integer addition. But 0.6 + 0.6 = 1.2 does not fit in the range. In two's complement an overflow wraps around and gives a number from the other end:
q15_t q15_add_wrap(q15_t a, q15_t b)
{
return (q15_t)(uint16_t)((uint16_t)a + (uint16_t)b);
}
The run: 19661 + 19661 (0.6 + 0.6) gave −26214, that is, −0.8. For an audio signal this is a loud click, for a controller a full-power command in the opposite direction. Saturating addition stops at the edge:
q15_t q15_add_sat(q15_t a, q15_t b)
{
return sat16((int32_t)a + b);
}
The same addition gave 32767 — 0.99997, the representable value nearest to 1.2.
The error is large, but in the right direction, and the signal does not flip over.
The sum of two int16_t in int32_t never overflows, so
limiting after addition in a wide type is always correct.
Wrap-around is written via uint16_t for a reason: overflow of a
signed int16_t in addition is impossible in C (the operands are promoted to
int, section 122), but converting 39322 to int16_t is behaviour
defined by the implementation; through an unsigned type the intention is explicit.
Sometimes wrap-around is exactly what is needed: the phase of an oscillator, an angle in "binary radians" where 0x8000 is ±180° — there crossing the edge is the correct arithmetic. Saturation is for signals and quantities, wrap-around is for cyclic quantities.
69а.4 Multiplication and rounding
The product of two Q15 numbers is Q30 in 32 bits. To return to Q15, shift right by 15:
q15_t q15_mul_trunc(q15_t a, q15_t b)
{
return sat16(((int32_t)a * b) >> 15);
}
A right shift discards the low bits — rounds down, towards minus infinity. The error of each multiplication is from 0 to almost −1 step, −0.5 step on average. In one multiplication this is invisible, but in a filter where the result is multiplied again and again (IIR), or in an accumulation of thousands of products, the systematic bias adds up to a constant offset of the output. It is fixed by adding half a step before the shift:
q15_t q15_mul(q15_t a, q15_t b)
{
return sat16(((int32_t)a * b + (1 << 14)) >> 15);
}
A run on 100000 random pairs against the exact product:
| Multiplication | mean bias, steps | maximum error, steps |
|---|---|---|
| shift (truncation) | −0.499 | 1.000 |
| with rounding | −0.0006 | 0.500 |
The bias is gone, the maximum error halved — at the cost of one addition. CMSIS-DSP does it differently in different places in its Q15 functions, so when comparing your code with the library, do not be surprised by a difference in the last bit.
Minus one times minus one. −32768 × −32768 = 2³⁰, after the shift — 32768, and that is already beyond the edge of Q15. Without saturation the number turns into −32768: minus times minus gave minus one (the run: −32768). With saturation — 32767. This is the only pair on which a Q15 multiplication leaves the range, but at full scale it does occur.
Q31 multiplication is the same in 64 bits:
q31_t q31_mul(q31_t a, q31_t b)
{
return sat32(((int64_t)a * b + (1LL << 30)) >> 31);
}
0.5 × 1/3 in Q31 gave 357913942 — that is 0.1666666670, the exact value is
0.1666666667. On Cortex-M3 and M4 the 64-bit product is one instruction,
SMLAL (multiply-accumulate into a register pair), on Cortex-M0 it is
a call to the library __aeabi_lmul: M0 has no 32 × 32 → 64 instruction.
69а.5 Saturation on Cortex-M: SSAT, QADD and what the compiler does
Cortex-M3 and M4 have the SSAT instruction — saturate a signed number to a
given number of bits in one instruction. Cortex-M4 (and M7, M33 with the
DSP extension) also has QADD and QSUB — saturating addition and subtraction of 32-bit numbers.
In C they are reached through the built-in functions of the
arm_acle.h header (in CMSIS the same instructions are called __SSAT and __QADD):
int16_t sat16(int32_t x)
{
#if defined(__ARM_FEATURE_SAT)
return (int16_t)__ssat(x, 16); /* одна команда SSAT */
#else
if (x > Q15_MAX)
return Q15_MAX;
if (x < Q15_MIN)
return Q15_MIN;
return (int16_t)x;
#endif
}
The macros __ARM_FEATURE_SAT and __ARM_FEATURE_DSP are defined by the compiler
itself from -mcpu: for Cortex-M3 the first one exists, for M4 both, for M0
neither, and then the portable branch works. Saturating Q31 addition:
q31_t q31_add_sat(q31_t a, q31_t b)
{
#if defined(__ARM_FEATURE_DSP)
return __qadd(a, b); /* одна команда QADD */
#else
return sat32((int64_t)a + b);
#endif
}
What the disassembly showed:
| Function | Cortex-M4F | Cortex-M0 |
|---|---|---|
sat16 via __ssat |
8 bytes, SSAT |
36 bytes, comparisons |
sat16_plain — the same with if |
32 bytes, 2 branches | 36 bytes |
q31_add_sat |
6 bytes, QADD |
64 bytes |
q15_mul |
16 bytes, SSAT |
32 bytes |
The most useful thing here is the second row. gcc 12 for Cortex-M4 did not
recognise saturation in the two ifs and left comparisons with branches: 32 bytes
instead of 8. So if speed matters, SSAT has to be requested explicitly —
with a built-in function. On M0 the portable code and the built-in give
the same thing — there is no instruction. Cortex-M3 has SSAT too: the disassembly
showed it in sat16, q15_mul and q15_add_sat, but no QADD — M3
has no DSP extension.
69а.6 Division
Division in fixed point is the most awkward. The quotient of two Q15 numbers is just a number, without a scale; to get Q15, the dividend is shifted left by 15 bits beforehand. The result makes sense only when |a| < |b|, otherwise it is beyond the edge:
q15_t q15_div(q15_t a, q15_t b)
{
int32_t n = (int32_t)a * 32768;
int32_t half = (b > 0 ? b : -b) / 2;
n += (n >= 0) ? half : -half; /* округление к ближайшему: модуль на полшага больше */
return sat16(n / b);
}
Division in C truncates the fraction towards zero, so for rounding to nearest the magnitude of the dividend is increased by half the magnitude of the divisor. The run: 0.25 / 0.75 = 10923 (the exact value is 10922.67); −0.125 / 0.5 = −8192; 0.5 / −1 = −16384; 0.5 / 0.25 = 2 — beyond the edge, saturated to 32767.
On Cortex-M3 and M4 division is the SDIV instruction (the disassembly showed it in
q15_div); its time depends on the operands, and the ARM reference gives
a range rather than one number. Cortex-M0 has no hardware division at all:
q15_div calls __aeabi_idiv. Therefore division in the working loop
is replaced by multiplication by a precomputed reciprocal: "divide
by the gain" → "multiply by 1/k computed at setup".
Division by a power of two is a shift (with the caveat about negative numbers from
section 122).
69а.7 A filter in Q15 and Q31: the accumulator and guard bits
A typical job for Q15 is an FIR filter: the sum of products of samples and
coefficients. Each product is Q30, there are 16 of them, and the sum can be larger than
one product. If it is accumulated in int32_t, there is almost no headroom: Q30 in
32 bits leaves one integer bit and the sign. So the accumulator is 64-bit, and
rounding and saturation happen once, at the end:
q15_t fir_q15(const q15_t *h, const q15_t *x)
{
int64_t acc = 0; /* Q30 с запасом на сумму */
for (int k = 0; k < FIR_TAPS; k++)
acc += (int32_t)h[k] * x[k];
return sat16((int32_t)((acc + (1 << 14)) >> 15));
}
On Cortex-M4 the loop body is one SMLALBB instruction: multiply the low
halves of two registers as 16-bit numbers and add to the 64-bit
accumulator. On M3 it is SMLAL. On M0 the 64-bit accumulator costs
a pair of additions with carry — without library calls, but the function is twice as
long: 100 bytes against 52.
For Q31 the product is Q62, the accumulator is also 64 bits, and one bit of headroom remains:
q31_t fir_q31(const q31_t *h, const q31_t *x)
{
int64_t acc = 0; /* Q62: хватает, пока сумма |h| меньше 2 */
for (int k = 0; k < FIR_TAPS; k++)
acc += (int64_t)h[k] * x[k];
return sat32((acc + (1LL << 30)) >> 31);
}
The overflow limit is the sum of the magnitudes of the coefficients. For the filter in the run (a Hamming window, cut-off at 0.1 of the sampling rate, coefficients normalised to unity gain) it equals 1.050 — more than one because of the negative lobes, but less than two, so 64 bits are enough. For a filter with a large gain the input is divided by 2 or 4 beforehand — CMSIS-DSP describes exactly such scaling for its Q31 functions.
69а.8 Accuracy against float
The same 16-tap filter was run on 2048 samples — two sines and noise with
a peak value of about 0.9 — in three variants against a reference in double:
| Variant | maximum error | error in Q15 steps | signal-to-error ratio, dB |
|---|---|---|---|
| Q15, 64-bit accumulator | 4.30e-05 | 1.41 | 84.8 |
| float (single) | 8.65e-08 | 0.0028 | 143.1 |
| Q31, 64-bit accumulator | 1.13e-09 | 0.000037 | 175.0 |
Q15 gives about 85 dB — this is the quantization error of the 16-bit input and
coefficients, at the level of a 16-bit ADC. float is 58 dB more accurate: it has
24 significant bits. Q31 is another 32 dB more accurate than float — 31 bits of fraction against
24 bits of mantissa.
Hence a practical rule. For a signal from a 12-bit ADC (about 74 dB
of dynamic range) Q15 is more than enough — the filter error is smaller than the
error of the ADC itself. For IIR filters with poles near the unit circle,
where coefficient error shifts the cut-off frequency, and for long
accumulations Q15 is too little — Q31 or float is needed. And on a part without an FPU
Q31 turns out to be both more accurate and cheaper than float.
The other side: float has a huge range, Q15 has −1 to 1.
A signal that is a thousand times weaker in some parts than in others loses accuracy in
Q15 in the weak parts — float has the same relative accuracy
at any level. Fixed point requires knowing the range of the
quantity in advance.
69а.9 When fixed point is needed
Cortex-M0, M0+ and M3 — no FPU. Every float operation is a
library call. A program for M0 that computes the same FIR filter once
was built completely: in float the code section is 1520 bytes, in Q15 — 128 bytes.
The difference is the library: __aeabi_fadd 772 bytes, __aeabi_fmul 636 bytes and
the helper __clzsi2 60 bytes. The time of one software float operation is
tens of cycles against one or two for an integer multiplication (an estimate, not a measurement;
nothing was measured on silicon here), and a 16-tap FIR is 32 such calls
per sample.
Cortex-M4F, M7, M33 with an FPU — single-precision float is in hardware.
The float filter on M4F is 36 bytes, multiplication and addition are the
VMUL.F32 and VADD.F32 instructions. Here fixed point is needed less often: when
the data are already integers (ADC, DAC, codecs) and converting back and forth costs more than the
processing itself; when accuracy above float is needed (Q31); when
bit-identical operation on different parts is needed; when the DSP
SIMD instructions that process two pairs of Q15 at once are used.
Hardware accelerators work only in fixed point: CORDIC (section 46а) takes and returns Q1.31 and Q1.15, the G4 FMAC (section 46б) — Q1.15. The code that feeds them has to speak Q formats.
Neural networks in int8 (section 119) are the same fixed point with a scale and a zero point, only in 8 bits.
Sizes of the section's functions:
| Function | M4 code bytes | M4 frame | M0 code bytes | M0 frame |
|---|---|---|---|---|
q15_mul |
16 | 0 | 32 | 0 |
q31_mul |
38 | 0 | 52 | 8 |
q15_div |
32 | 0 | 60 | 8 |
q15_from_float |
100 | 0 | 96 | 8 |
fir_q15 |
52 | 16 | 100 | 32 |
fir_q31 |
84 | 8 | 104 | 24 |
fir_float |
36 | 0 | 36 | 24 |
fir_float on M0 has the same 36 bytes as on M4F — but that is only the loop body
with two library calls; the library itself is another kilobyte and a
half.
69а.10 Where Q15 and Q31 appear in the handbook
Section 69.9 is the first acquaintance with Q15 and Q16.16. Section 81а is
FIR and IIR on CMSIS-DSP, where every function has _q15, _q31
and _f32 variants; the rules of saturation and guard bits there are the same as here.
The Goertzel algorithm of 81б in fixed point requires exactly the
overflow control described in 69а.7. The hardware CORDIC (46а) and FMAC
(46б) take arguments in Q1.31 and Q1.15. The microstepping of the gauge stepper
(57ж) keeps its sine table in Q15. Quantizing a neural network to int8
(section 119) and the convolutional network in int8 (121м) use Q31 multipliers to
rescale between layers.
69а.11 Pitfalls
−1 × −1 without saturation. 32768 does not fit in Q15, and the product becomes −1. It occurs at full scale; saturate after each multiplication or guarantee that −32768 does not reach the input.
Truncation instead of rounding. A right shift biases the result by −0.5 step on average; in an IIR filter and in accumulation the bias builds up. Add half a step before the shift.
Wrap-around addition in a signal. 0.6 + 0.6 = −0.8: a click in audio, a jerk in a controller. Saturation; wrap-around only for phase and angles.
A 32-bit accumulator. The sum of 16 Q30 products goes beyond int32_t.
A 64-bit accumulator, rounding and saturation once at the end.
Hoping the compiler will insert SSAT by itself. gcc 12 for Cortex-M4
left two comparisons with branches — 32 bytes instead of 8. The built-in
__ssat or __SSAT from CMSIS.
Division in the working loop on M0. There is no hardware division —
__aeabi_idiv for every sample. Multiply by a reciprocal
computed in advance.
"Just a little" float in M0 firmware. One line with float in
the processing — and a kilobyte and a half of library arrives in the firmware.
Check the .map for __aeabi_f*.
Q31 from float. float has 24 significant bits; a Q31 obtained by converting
from float is no more accurate than float. Compute Q31 coefficients in double or
in advance, on the computer.
The scale in your head. Is the variable int16_t speed Q15, Q8.7 or
just an integer? A named type (q15_t) and a comment with the format for every
quantity; when the format changes — a shift with an explicit comment.
69а.12 Summary
- Qm.n: m bits of signed integer part, n of fraction; Q15 is from −1 to 0.99997 with a step of 3.05·10⁻⁵, Q31 has a step of 4.66·10⁻¹⁰.
- Conversion from
float— multiply by 2ⁿ, round, saturate; Q31 fromfloatis no more accurate than 24 bits. - Addition: 0.6 + 0.6 with wrap-around gives −0.8, with saturation 0.99997.
- Multiplication with rounding removes the −0.5 step bias and halves the maximum error; saturate −1 × −1.
SSATandQADDare one instruction on M4 (SSATexists on M3 too), but gcc 12 does not insertSSATby itself: 32 bytes withifagainst 8 via__ssat.- Division is
SDIVon M3/M4, a library on M0; in a loop — multiplication by the reciprocal. - A 16-tap FIR: Q15 — 84.8 dB,
float— 143.1 dB, Q31 — 175.0 dB. - On M0 a
floatfilter pulls in 1520 bytes of code against 128 in Q15.
Next: section 70 "Structures and files".