02. Quantisation and dither

Sampling (notebook 01) makes time discrete; quantisation makes amplitude discrete. A 16-bit file can store only 65 536 different values, so every sample is rounded, and the rounding error behaves like added noise. The level of that noise, and whether it is heard as noise or as distortion, determine how many bits a recording needs and how to reduce bit depth without degrading quiet passages such as a fading voice or a reverb tail.

Learning outcomes. After working through this notebook you can

  • describe the library’s (asymmetric) integer/float scaling and requantise a signal by hand, bit for bit;

  • derive the \(6.02\,b + 1.76\) dB SQNR rule and confirm it by measurement;

  • explain why quantising a quiet signal produces distortion, and remove it with TPDF dither;

  • predict the noise cost of dither (4.77 dB).

import matplotlib.pyplot as plt
import numpy as np

import audio_samples as aus
from audio_samples.utils import snr

rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
I16, U8, AS_F64 = aus.SampleType.I16, aus.SampleType.U8, aus.SampleType.F64

def through(x, fmt, fs=16_000):
    # Convert a float array to the sample format `fmt` and back to float64 with the library.
    return aus.AudioSamples.new_mono(np.asarray(x, dtype=float), sample_rate=fs).to_format(fmt).to_format(AS_F64).to_numpy()

def power(v):
    return float(np.mean(np.square(v)))

Concept

Uniform quantisation maps a sample \(x\) on the normalised scale \([-1, 1]\) to an integer code \(q\) and back. This library uses an asymmetric mapping so that both \(-1\) and \(+1\) are reachable and the integer round trip is exact:

\[q = \mathrm{round}(x \cdot 2^{b-1}) \;\; (x < 0), \qquad q = \mathrm{round}\big(x \cdot (2^{b-1} - 1)\big) \;\; (x \ge 0)\]

where \(b\) is the word length in bits, \(x\) is clamped to \([-1, 1]\) and \(\mathrm{round}\) rounds half away from zero. Converting back divides by the same factors. The step size (one least-significant bit, LSB, in units of full scale) is therefore

\[\Delta = 2^{1-b} \;\; \text{(below zero)}, \qquad \Delta_+ = \frac{1}{2^{b-1} - 1} \;\; \text{(above zero)}\]

For \(b = 16\): \(\Delta = 1/32768\) and \(\Delta_+ = 1/32767\), a difference of 0.003 %. (A symmetric mapping divides by \(2^{b-1}\) on both sides.)

Quantisation noise. If the signal is busy enough, the rounding error \(e = \hat{x} - x\) is spread uniformly over one step, \([-\Delta/2, \Delta/2]\), so its power is

\[\sigma_e^2 = \frac{\Delta^2}{12}\]

in units of full scale squared, where \(\hat{x}\) is the quantised value.

SQNR of a full-scale sine. A sine of amplitude 1 has power \(1/2\). With \(\Delta = 2/2^b\):

\[\mathrm{SQNR} = 10 \log_{10} \frac{1/2}{\Delta^2/12} = 10\log_{10}\!\left(\tfrac{3}{2} \, 4^{b}\right) \approx 6.02\,b + 1.76 \ \mathrm{dB}\]

Each extra bit adds about 6 dB. A signal peaking \(L\) dB below full scale loses \(L\) dB of SQNR.

Dither. For a quiet signal only a few steps tall, the error is not uniform noise: it is a deterministic function of the signal, so it repeats with the signal and shows up as harmonics (distortion). TPDF dither adds, before rounding, a random value \(d = u_1 + u_2\) where \(u_1, u_2\) are independent and uniform on \([-\Delta/2, \Delta/2)\); \(d\) has a triangular density on \([-\Delta, \Delta]\) and power \(\Delta^2/6\). The total error power becomes

\[\sigma^2_{e,\mathrm{TPDF}} = \frac{\Delta^2}{12} + \frac{\Delta^2}{6} = \frac{\Delta^2}{4}\]

i.e. \(10\log_{10} 3 \approx 4.77\) dB more noise, but the error’s mean and variance no longer depend on the signal: the distortion is replaced by steady noise. The library applies no dither in any conversion, so this notebook implements it with NumPy.

With the library

The library’s convention, step sizes and the SQNR at 16 bits through the int16 conversion (AudioSamples.to_format(SampleType.I16)), measured with audio_samples.utils.snr:

# The asymmetric mapping: -1 -> -32768, +1 -> 32767.
edge = aus.AudioSamples.new_mono(np.array([-1.0, -0.5, 0.0, 0.5, 1.0]), sample_rate=16_000)
codes = edge.to_format(I16).to_numpy()
print(codes)
assert codes.tolist() == [-32768, -16384, 0, 16384, 32767]
# ... and back: 16384 / 32767 is not exactly 0.5.
print(edge.to_format(I16).to_format(AS_F64).to_numpy())
assert abs(through([0.5], I16)[0] - 16384 / 32767) < 1e-15

# Full-scale 997 Hz sine at 48 kHz, 1 s, rounded to int16 and back.
x = aus.sine_wave(997.0, 1.0, sample_rate=48_000, dtype=F64)
back = x.to_format(I16).to_format(AS_F64)
err = aus.AudioSamples.new_mono(back.to_numpy() - x.to_numpy(), sample_rate=48_000)
measured = snr(x, err)
predicted = 10 * np.log10(1.5 * 4.0 ** 16)
print(f"SQNR at 16 bits: predicted {predicted:.2f} dB, measured {measured:.2f} dB")
assert abs(predicted - 98.09) < 0.01
assert abs(measured - predicted) < 0.05      # measured: 98.10 dB
assert abs(measured - 98.10) < 0.005
[-32768 -16384      0  16384  32767]
[-1.         -0.5         0.          0.50001526  1.        ]
SQNR at 16 bits: predicted 98.09 dB, measured 98.10 dB

Now the quiet case: a 997 Hz sine of amplitude 2.5 LSB (5 LSB peak to peak) at 16 kHz, rounded to int16 with and without TPDF dither. The dither is two independent uniform variables on \([-\Delta/2, \Delta/2)\) from NumPy’s generator. (The library’s aus.white_noise(..., amplitude=A, seed=...) is also uniform on \([-A, A)\) and gives the same result with \(A = \Delta/2\); exercise 3 uses NumPy too.)

fs = 16_000
lsb = 1.0 / 32768.0
xq = aus.sine_wave(997.0, 1.0, sample_rate=fs, amplitude=2.5 * lsb, dtype=F64).to_numpy()

dither = rng.uniform(-lsb / 2, lsb / 2, xq.size) + rng.uniform(-lsb / 2, lsb / 2, xq.size)
e_plain = through(xq, I16) - xq
e_dith = through(xq + dither, I16) - xq

ratio_plain = power(e_plain) / (lsb ** 2 / 12)
ratio_dith = power(e_dith) / (lsb ** 2 / 12)
print(f"error power / (LSB^2/12): undithered {ratio_plain:.2f}, dithered {ratio_dith:.2f}")
# Dithered error power is LSB^2/4 = 3 x (LSB^2/12); a 16 000-sample estimate is good to ~2 %.
assert abs(ratio_dith - 3.0) < 0.1
assert abs(ratio_plain - 1.23) < 0.005       # deterministic: no randomness involved

def spur_db(e):
    # Error power in the 3rd-harmonic bin (2991 Hz) relative to the mean bin power, in dB.
    m = aus.AudioSamples.new_mono(e, sample_rate=fs).rfft(16_000)[0]   # 1 Hz bins (magnitudes)
    return 10 * np.log10(m[2991] ** 2 / np.mean(m ** 2))

def corr(e):
    return np.sum(e * xq) / (np.sqrt(power(e) * power(xq)) * xq.size)

print(f"3rd-harmonic spur: {spur_db(e_plain):+.1f} dB undithered, {spur_db(e_dith):+.1f} dB dithered")
print(f"error/signal correlation: {corr(e_plain):+.3f} undithered, {corr(e_dith):+.3f} dithered")
assert abs(spur_db(e_plain) - 31.9) < 0.05   # a clear harmonic
assert spur_db(e_dith) < 3.0                 # noise only
assert abs(corr(e_plain) - (-0.516)) < 0.001 # half correlated with the signal
assert abs(corr(e_dith)) < 0.03              # uncorrelated
error power / (LSB^2/12): undithered 1.23, dithered 3.00
3rd-harmonic spur: +31.9 dB undithered, -4.4 dB dithered
error/signal correlation: -0.516 undithered, +0.003 dithered
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
n = np.arange(64)
axes[0].plot(n / fs * 1000, xq[:64] / lsb, label="input")
axes[0].step(n / fs * 1000, (xq + e_plain)[:64] / lsb, where="mid", label="int16, no dither")
axes[0].set(xlabel="Time (ms)", ylabel="Amplitude (LSB)", title="A 2.5 LSB sine")
axes[0].legend(fontsize=7)
f = np.arange(8001)
for e, lab in [(e_plain, "no dither"), (e_dith, "TPDF dither")]:
    m = aus.AudioSamples.new_mono(e, sample_rate=fs).rfft(16_000)[0]
    axes[1].plot(f, 20 * np.log10(m / 16_000 + 1e-20), lw=0.6, label=lab)
axes[1].set(xlabel="Frequency (Hz)", ylabel="Error level (dB re full scale)", title="Error spectrum",
            ylim=(-180, -100))
axes[1].legend(fontsize=7)
fig.tight_layout()
plt.show()
../_images/03f7116b5c61398ee0be824ed711e1ce73cb47559b3ab5e9ea41247f36613a7c.png

Dither tripled the error power, but the result is better: the undithered error is half correlated with the signal and is concentrated at harmonics of 997 Hz, which are heard as distortion, while the dithered error has a flat spectrum.

How it works

Write the requantiser in NumPy with the same convention, check that it is bit-identical to the library’s 16-bit and 8-bit (u8, offset binary) round trips, then measure SQNR at several word lengths against \(6.02\,b + 1.76\).

Note that np.round rounds half to even (np.round(2.5) == 2.0), while the library rounds half away from zero, so we write that rounding explicitly.

def round_half_away(v):
    return np.sign(v) * np.floor(np.abs(v) + 0.5)

def requantise(x, b):
    half = 2.0 ** (b - 1)
    x = np.clip(x, -1.0, 1.0)
    return np.where(x < 0, round_half_away(x * half) / half, round_half_away(x * (half - 1)) / (half - 1))

assert np.round(2.5) == 2.0 and round_half_away(2.5) == 3.0
# A tie: 2.5 steps on the positive side rounds away from zero to 3 in the library.
assert through([2.5 / 32767], I16)[0] * 32767 == 3.0

xs = x.to_numpy()                                  # full-scale 997 Hz at 48 kHz
assert np.allclose(through(xs, I16, fs=48_000), requantise(xs, 16), rtol=0, atol=1e-15)
assert np.allclose(through(xs, U8, fs=48_000), requantise(xs, 8), rtol=0, atol=1e-15)

p_signal = power(xs)
measured_sqnr = {}
for b, expected in [(4, 25.62), (8, 49.98), (12, 74.03), (16, 98.10)]:
    sqnr = 10 * np.log10(p_signal / power(requantise(xs, b) - xs))
    measured_sqnr[b] = sqnr
    rule = 6.02 * b + 1.76
    print(f"{b:2d} bits: measured {sqnr:6.2f} dB, rule {rule:6.2f} dB")
    assert abs(sqnr - expected) < 0.01
    # The rule of thumb: within 0.25 dB at 4 and 8 bits (the error is less uniform when the steps
    # are coarse), within 0.05 dB from 12 bits up.
    assert abs(sqnr - rule) < (0.05 if b >= 12 else 0.25)
 4 bits: measured  25.62 dB, rule  25.84 dB
 8 bits: measured  49.98 dB, rule  49.92 dB
12 bits: measured  74.03 dB, rule  74.00 dB
16 bits: measured  98.10 dB, rule  98.08 dB

At 16 bits the effect of the asymmetry is small. The positive-half step is larger by a factor \(32768/32767\), i.e. by \(3.05\times10^{-5}\) (0.003 %); averaging the two halves’ noise powers changes the noise by about \(3\times10^{-5}\), about 0.0001 dB:

eps = 32768 / 32767 - 1
assert abs(eps - 3.05e-5) < 1e-7
assert abs(100 * eps - 0.003) < 0.0001             # 0.003 %
noise_ratio = (1 + (1 + eps) ** 2) / 2
assert abs(noise_ratio - 1 - 3.05e-5) < 1e-7
assert 10 * np.log10(noise_ratio) < 1.4e-4          # about 0.0001 dB
# The numbers quoted in the Concept section:
assert 2 ** 16 == 65_536
assert abs(10 * np.log10(3) - 4.77) < 0.005

Integer-to-integer conversions are a separate path. Narrowing int32 to int16 shifts bits (truncating towards \(-\infty\), a \(-\tfrac12\) LSB bias), while conversions to u8 rescale with the asymmetric factors and round to nearest. Go through float64 if you want rounding everywhere.

v = np.array([-65537, -65536, -1, 0, 65535, 65536], dtype=np.int32)
i32 = aus.AudioSamples.new_mono(v, sample_rate=8_000)
narrowed = i32.to_format(I16).to_numpy()
print(narrowed)
assert narrowed.tolist() == (v >> 16).tolist() == [-2, -1, -1, 0, 0, 1]

# int16 -> u8 rounds: 255/32767 * 127 = 0.99 -> 1, whereas a bit shift (255 >> 8) would give 0.
i16 = aus.AudioSamples.new_mono(np.array([-1, 128, 255], dtype=np.int16), sample_rate=8_000)
centred = i16.to_format(U8).to_numpy().astype(int) - 128
assert centred.tolist() == [0, 0, 1]
[-2 -1 -1  0  0  1]

Ask the library to explain

aus.explain.quantisation(bits) states the convention, the step sizes, the noise level, the SQNR and the SQNR you would get with TPDF dither.

Which dBFS? dBFS means decibels relative to digital full scale, an amplitude of 1. A peak level is \(20\log_{10}\) of the peak amplitude (dBFS peak); an RMS level is \(20\log_{10}\) of the RMS, i.e. \(10\log_{10}\) of the mean square (dBFS RMS). A full-scale sine is therefore 0 dBFS peak but \(-3.01\) dBFS RMS. The explainer’s “Noise level”, \(10\log_{10}(\Delta^2/12) = -101.10\) dB at 16 bits, is in dB re 1, the power of a full-scale DC level: an RMS level in this convention. AES17 instead calibrates RMS levels so that a full-scale sine reads 0 dBFS, which adds 3.01 dB: the same noise is \(-98.09\) dBFS (AES17).

doc = aus.explain.quantisation(16)
assert doc.quantity("Quantisation levels") == 65_536
assert doc.quantity("Step size (negative half)") == 1 / 32768
assert abs(doc.quantity("Step size (positive half)") - 1 / 32767) < 1e-18
sqnr16 = doc.quantity("SQNR (full-scale sine)")
assert abs(sqnr16 - 98.09) < 0.01 and abs(doc.quantity("Rule of thumb") - 98.09) < 0.01
assert abs(sqnr16 - doc.quantity("SQNR with TPDF dither") - 4.77) < 0.01   # 10 log10 3
assert abs(doc.quantity("Noise level") - (-101.10)) < 0.01                 # dB re 1 (full-scale DC)
assert abs(10 * np.log10((1 / 32768) ** 2 / 12) - doc.quantity("Noise level")) < 1e-9
assert abs(10 * np.log10(0.5) + 3.01) < 0.01                                # full-scale sine, RMS
assert abs(doc.quantity("Noise level") - 10 * np.log10(0.5) - (-98.09)) < 0.01  # AES17
assert doc.has_warning_containing("i16")
doc

Quantisation

16-bit quantisation maps each sample to one of 65536 levels, 3.0518e-5 apart on the [-1, 1] scale. For a full-scale sine the rounding noise is 98.0905 dB below the signal.

Formulas

Float to integer as implemented (x clamped to [-1, 1], round half away from zero):

$$ q = \begin{cases} \mathrm{round}(x \cdot 2^{b-1}) & x < 0 \ \mathrm{round}(x \cdot (2^{b-1} - 1)) & x \geq 0 \end{cases} $$

Step size over the full scale [-1, 1):

$$ \Delta = \frac{2}{2^{b}} = 2^{1-b} $$

Noise power of rounding error uniformly distributed in one step:

$$ \sigma_e^2 = \frac{\Delta^2}{12} $$

Signal-to-quantisation-noise ratio of a full-scale sine: signal power 1/2 over noise power Δ²/12:

$$ \mathrm{SQNR} = 10 \log_{10} \frac{6}{\Delta^2} \approx 6.02,b + 1.76 \ \mathrm{dB} $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $b$ | word length | 16 bits | | $\Delta$ | quantisation step | 3.0518e-5 | | $x$ | sample value on the normalised [-1, 1] scale | | | $q$ | integer code | |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Quantisation levels | $L$ = 65536 | $2^{b}$ | | Step size (negative half) | $\Delta$ = 3.0518e-5 | $2^{1-b}$ | | Step size (positive half) | $\Delta_+$ = 3.0519e-5 | $1 / (2^{b-1} - 1)$ | | Noise power | $\sigma_e^2$ = 7.7610e-11 | $\Delta^2 / 12$ | | Noise level | $10 \log_{10} \sigma_e^2$ = -101.101 dB re 1 (power of a full-scale DC level) | $10 \log_{10}(\Delta^2/12)$ | | Noise level (AES17 dBFS) | $10 \log_{10} (2 \sigma_e^2)$ = -98.0905 dBFS (AES17: full-scale sine = 0 dBFS) | $10 \log_{10}(\Delta^2/12) + 10 \log_{10} 2$ | | SQNR (full-scale sine) | $SQNR$ = 98.0905 dB | $10 \log_{10}((1/2)/(\Delta^2/12))$ | | Rule of thumb | $20 \log_{10}(2) , b + 10 \log_{10}(1.5)$ = 98.0905 dB | $\text{exact form of } 6.02,b + 1.76 \text{ (the rounded constants give 0.01 dB less at 16 bits)}$ | | SQNR with TPDF dither | $\mathrm{SQNR}d$ = 93.3193 dB | $\mathrm{SQNR} - 10 \log{10} 3$ |

Trade-offs

  • Each extra bit halves the step size and raises the SQNR by about 6.02 dB.

  • Triangular (TPDF) dither of ±1 step adds noise of power Δ²/6, raising total noise to Δ²/4 (about 4.77 dB worse) but making the error independent of the signal, which removes distortion on quiet signals.

  • This crate’s float-to-integer conversion rounds without dither; add dither yourself before requantising quiet material.

  • The SQNR formula assumes a full-scale signal; a signal peaking 20 dB below full scale loses 20 dB of SQNR.

Warnings

  • Info: 16 bits is the word length of this crate’s i16 sample type.

See also

  • Type conversion: audio_samples::AudioTypeConversion::to_format

  • Type conversion (Python): audio_samples.AudioSamples.to_format

  • Python: audio_samples.explain.quantisation

Exercises

  1. How many bits do you need for an SQNR of at least 90 dB on a full-scale sine? Predict from the rule, then confirm by measurement (with requantise) at that word length and one bit fewer.

answer = None  # TODO
# Solution
answer = int(np.ceil((90 - 1.76) / 6.02))        # 14.66 -> 15 bits
assert answer == 15
sqnr_at = lambda b: 10 * np.log10(power(xs) / power(requantise(xs, b) - xs))
assert sqnr_at(15) >= 90.0 and sqnr_at(14) < 90.0
  1. A sine peaks at \(-20\) dBFS peak (amplitude 0.1) and is stored as int16. Predict its SQNR in dB, then measure it with the library conversion and snr.

answer = None  # TODO
# Solution
answer = 98.09 - 20.0                            # 78.09 dB
quiet = aus.sine_wave(997.0, 1.0, sample_rate=48_000, amplitude=0.1, dtype=F64)
e = aus.AudioSamples.new_mono(quiet.to_format(I16).to_format(AS_F64).to_numpy() - quiet.to_numpy(),
                              sample_rate=48_000)
assert abs(snr(quiet, e) - answer) < 0.1
  1. Predict how much TPDF dither lowers the SQNR (in dB) of a loud sine (amplitude 0.9) quantised to 8 bits, and measure it.

answer = None  # TODO
# Solution
answer = 10 * np.log10(3)                        # 4.77 dB
lsb8 = 1.0 / 128.0                               # one step at 8 bits
loud = aus.sine_wave(997.0, 1.0, sample_rate=48_000, amplitude=0.9, dtype=F64).to_numpy()
d = rng.uniform(-lsb8 / 2, lsb8 / 2, loud.size) + rng.uniform(-lsb8 / 2, lsb8 / 2, loud.size)
sq = lambda y: 10 * np.log10(power(loud) / power(y - loud))
penalty = sq(requantise(loud, 8)) - sq(requantise(loud + d, 8))
# Random dither over 48 000 samples: the noise power estimate is good to ~1 %.
assert abs(penalty - answer) < 0.2

Common pitfalls

  • The library maps integers to floats asymmetrically (divide by \(2^{b-1}\) below zero, by \(2^{b-1}-1\) above). Compared with a symmetric mapping that divides by \(2^{b-1}\) on both sides, positive samples differ by up to about \(3\times10^{-5}\).

  • np.round rounds half to even; the library rounds half away from zero.

  • Integer-to-integer narrowing between signed types shifts bits (truncates towards \(-\infty\)); conversions to u8 round. Go through float64 if you want rounding everywhere.

  • No dither is applied by any conversion; add it yourself before reducing the bit depth of quiet material.

  • \(6.02\,b + 1.76\) dB is for a full-scale sine. Speech peaks well below full scale and has a high crest factor; its SQNR is much lower.

  • aus.white_noise is uniform, not Gaussian: amplitude \(A\) gives RMS \(A/\sqrt{3}\).

See also

References

  • Lipshitz, S. P., Wannamaker, R. A. and Vanderkooy, J. (1992). Quantization and dither: a theoretical survey. Journal of the Audio Engineering Society, 40(5), 355-375.

  • Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Section 4.8 (quantisation error in A/D conversion).