Signals, Sampling and Quantisation¶
Every physical measurement that unfolds across time or space, from the vibration of a violin string to the millivolt ripple of a human brainwave, is a signal carrying information about the world. This section builds the mathematical foundations of continuous and discrete signals, explains why rotating complex phasors simplify wave physics, and shows how sampling and quantisation turn smooth analogue reality into faithful digital numbers.
What a Signal Actually Is¶
-
Imagine standing beside a busy harbour at dusk and watching a floating buoy bob up and down on the water. At every instant in time, that buoy sits at one particular height above the calm seabed. If you trace its height on a long strip of paper as the minutes pass, the resulting wavy ink line is a signal, meaning a measurable quantity that varies as a function of an independent variable such as time, space, or frequency.
-
Signals form the universal language shared across physics, engineering, biology, and modern AI. In acoustics, a microphone converts microscopic air-pressure fluctuations into a voltage waveform, which becomes the starting point for speech recognition and music generation in Chapter 10. Inside a hospital or a neuroscience lab, scalp electrodes record microvolt electroencephalogram (EEG) brainwaves whose rhythms track sleep, attention, and epilepsy, a foundation we return to in Chapter 12 (NeuroAI) and Chapter 24 (BioAI). Radar antennas measure reflected radio echoes to track approaching aircraft, seismometers record ground velocity to locate earthquakes, and financial order books record asset prices tick by tick across trading sessions.
-
Mathematically, a one-dimensional continuous-time signal is a function \(x(t)\) defined for every real instant \(t \in \mathbb{R}\), using round parentheses to signal that time flows without gaps. A discrete-time signal is a sequence \(x[n]\) indexed only at integer steps \(n \in \mathbb{Z}\), using square brackets to remind us that values exist strictly at discrete snapshots. Nature largely operates in continuous time, while digital computers can only store and process discrete sequences of finite-precision numbers.
Sinusoids and Complex Exponentials¶
- Before you can analyse a complex recording like a symphony or a heartbeat, you need the simplest possible building block. Think of a child pushing a playground swing back and forth with steady rhythm. The swing's horizontal position traces out a smooth sinusoid, defined by three intuitive parameters.
-
Here \(A \ge 0\) is the amplitude (how far the swing travels from centre), \(f\) is the frequency in hertz (complete cycles per second, linked to angular frequency \(\omega = 2\pi f\) in radians per second), and \(\phi\) is the phase in radians (where in its cycle the swing happened to start at \(t = 0\)). Every pure musical note, radio carrier, and oscillating pendulum follows this exact shape.
-
Working directly with sums of sines and cosines quickly gets messy because shifting a cosine in time forces you to juggle awkward trigonometric identities like \(\cos(\alpha + \beta) = \cos\alpha\cos\beta - \sin\alpha\sin\beta\). Signal processing sidesteps that entire headache using Euler's formula, one of the cleanest bridges in all of mathematics.
-
Notice that electrical engineers write \(j = \sqrt{-1}\) instead of \(i\) so it never collides with electrical current. Picture \(e^{j\omega t}\) as the glowing tip of a clock hand of length \(1\) spinning counter-clockwise around the unit circle in the complex plane at constant angular speed \(\omega\). We call this spinning arrow a complex phasor. As it turns smoothly around the circle, its horizontal shadow on the real axis traces \(\cos(\omega t)\), while its vertical shadow on the imaginary axis traces \(\sin(\omega t)\).
-
Why is the rotating phasor so magical? Because time shifts become plain multiplication! Delaying the rotating arrow by \(t_0\) seconds simply multiplies it by a constant complex rotation \(e^{-j\omega t_0}\), since \(e^{j\omega(t - t_0)} = e^{-j\omega t_0} e^{j\omega t}\). Even better, any real cosine can be written as the average of two phasors spinning in opposite directions at speeds \(+\omega\) and \(-\omega\).
- That simple identity immediately demystifies negative frequencies, a phrase that puzzles nearly every newcomer. A negative frequency \(-\omega\) does not mean time is flowing backwards or cycles happen fewer than zero times per second. It simply represents a second arrow spinning clockwise at the exact same speed so that the two imaginary vertical components cancel out cleanly, leaving a purely real horizontal cosine wave.
Energy, Power, RMS, and Decibels¶
-
Suppose you record two very different sounds. The first is a brief handclap that bursts loudly for twenty milliseconds and then fades into complete silence. The second is the steady hum of a refrigerator running all afternoon. Both are signals, yet comparing their size requires slightly different yardsticks.
-
For a transient signal that eventually dies away, we measure its total signal energy \(E\) by summing (or integrating) its squared magnitude across all time.
- A steady unending signal like a pure cosine or an eternal refrigerator hum has infinite total energy (\(E = \infty\)), so we instead measure its average power \(P\), meaning energy per unit time.
-
Taking the square root of the average power gives the root-mean-square (RMS) amplitude \(x_{\text{rms}} = \sqrt{P}\). Physically, RMS tells you the constant direct-current voltage that would heat a resistor at the exact same rate as your oscillating signal. For any pure sinusoid of peak amplitude \(A\), a quick integral shows that \(P = A^2 / 2\), so \(x_{\text{rms}} = A / \sqrt{2} \approx 0.707\,A\).
-
Real-world signals span mind-bending dynamic ranges. A jet engine at take-off carries roughly a trillion times more acoustic power than the faintest whisper a healthy human ear can detect. Writing ratios like \(10^{12}\) or \(0.000001\) on every audio mixer or radar display would be unreadable, so engineers compress ratios onto the logarithmic decibel (dB) scale.
- Notice the factor of \(20\) for amplitude versus \(10\) for power, which arises directly because power scales with squared amplitude (\(P \propto A^2\), and \(\log_{10}(A^2) = 2\log_{10}(A)\)). Three quick mental benchmarks make decibels second nature. Doubling power adds \(+3\,\text{dB}\), doubling amplitude (four times the power) adds \(+6\,\text{dB}\), and multiplying power by ten adds \(+10\,\text{dB}\) (while multiplying amplitude by ten adds \(+20\,\text{dB}\)).
Sampling and the Nyquist-Shannon Theorem¶
- To bring a continuous-time analogue signal \(x(t)\) inside a computer, an analogue-to-digital converter (ADC) measures its voltage at uniform intervals spaced \(T_s\) seconds apart, giving the sampling rate \(f_s = 1 / T_s\) samples per second.
- At first glance, throwing away the infinitely many instants between snapshots sounds recklessly lossy. How could a finite grid of dots ever preserve every subtle wiggle of a smooth continuous waveform? Astonishingly, if the signal contains no frequency components higher than \(f_{\max}\) (we call it band-limited to \(f_{\max}\)), zero information is lost as long as you sample strictly faster than twice that maximum frequency!
-
This celebrated result is the Nyquist-Shannon sampling theorem. The minimum safe speed \(2 f_{\max}\) is the Nyquist rate, and half the sampling rate, \(f_N = f_s / 2\), is the Nyquist frequency, representing the highest frequency a digital system running at \(f_s\) can faithfully distinguish. Compact discs sample audio at \(f_s = 44.1\,\text{kHz}\) precisely because human hearing tops out around \(20\,\text{kHz}\), leaving \(f_N = 22.05\,\text{kHz}\) with a comfortable margin above our auditory limit.
-
What happens if you break the rule and sample too slowly? Think of watching a spoked carriage wheel in an old Western film, or a helicopter rotor spinning under a flickering video camera. If the camera shoots 24 frames per second while a wheel spoke turns nearly a full step between frames, your eye connects consecutive snapshots along the shortest path and sees the wheel turning lazily backwards or even standing frozen!
-
That exact optical illusion in signal processing is called aliasing. When a tone of frequency \(f > f_s / 2\) gets sampled at rate \(f_s\), its discrete snapshots become mathematically identical to those of a much lower impostor frequency folded back into the base band \([0, f_s / 2]\).
-
For instance, if a sensor samples at \(f_s = 100\,\text{Hz}\) (Nyquist frequency \(50\,\text{Hz}\)) and a noisy \(85\,\text{Hz}\) motor vibration sneaks into the wire, the ADC records an indistinguishable phantom tone at \(|85 - 100| = 15\,\text{Hz}\). Once aliasing occurs, no digital algorithm on earth can untangle the impostor from a genuine \(15\,\text{Hz}\) signal, because their sample sequences are identical bit for bit.
-
That is why every serious data-acquisition system places an analogue anti-aliasing low-pass filter physically before the sampler. The analogue filter gently strips away frequencies above \(f_s / 2\) while the signal is still continuous, ensuring nothing high enough to masquerade as a low-frequency ghost ever reaches the ADC.
Quantisation, Noise, and the 6 dB per Bit Law¶
-
Sampling discretises the horizontal time axis, yet each snapshot \(x[n]\) is still a real number with infinitely many decimal digits. Digital memory can only store \(B\) binary bits per sample, providing \(L = 2^B\) discrete amplitude levels. Rounding each continuous sample to the nearest available staircase rung is called quantisation, and unlike safe Nyquist sampling, quantisation is genuinely irreversible.
-
Consider a uniform quantiser covering a full-scale amplitude range \([-V, +V]\) with \(L = 2^B\) equally spaced levels. The spacing between adjacent rungs is the step size \(\Delta\).
-
Whenever a sample falls inside the linear range, snapping it to the nearest level introduces a rounding error \(e[n] = x_q[n] - x[n]\) bounded tightly between \(-\Delta / 2\) and \(+\Delta / 2\). For a busy, smoothly varying signal crossing many levels (such as speech, music, or sensor telemetry), this error behaves remarkably like independent white noise spread uniformly across \([-\Delta / 2, +\Delta / 2]\) with probability density \(p(e) = 1 / \Delta\).
-
Integrating \(e^2 p(e)\) across one step immediately yields one of the most famous variance formulas in engineering.
- Now let us see how clean a full-scale sinusoid \(x(t) = V \cos(\omega t)\) sounds after \(B\)-bit uniform quantisation! Its average signal power is \(P_{\text{sig}} = V^2 / 2\). Substituting \(\Delta = 2V / 2^B\) into the quantisation noise power \(\sigma_q^2 = \Delta^2 / 12 = V^2 / (3 \cdot 2^{2B})\) gives the Signal-to-Quantisation-Noise Ratio (SQNR).
- Converting this ratio into decibels produces the celebrated 6 dB per bit rule that audio and hardware engineers recite by heart.
-
Every single bit you add to a converter doubles the number of levels, halves the step size \(\Delta\), cuts quantisation noise power by a factor of four, and hands you \(+6.02\,\text{dB}\) of extra dynamic range. That explains the numbers printed on consumer electronics everywhere. Early 8-bit video-game audio topped out near \(49.9\,\text{dB}\) (audible background hiss during quiet moments), 16-bit CD audio reaches a crystal-clear \(98.1\,\text{dB}\), and 24-bit studio recorders push theoretical resolution past \(146\,\text{dB}\) so engineers can capture whispers and drum hits without clipping.
-
Uniform quantisation has one practical weakness. Its error floor \(\Delta^2 / 12\) stays fixed regardless of whether the speaker is shouting or whispering. When a human voice drops to \(1\%\) of full scale, a uniform 8-bit quantiser wastes almost all its rungs on empty loud territory and leaves the whisper crushed onto only two or three coarse steps!
-
Telecommunications engineers solved this decades ago with non-uniform quantisation (known as companding, short for compressing and expanding), using logarithmic curves such as \(\mu\)-law in North America and Japan or A-law in Europe. Before uniform rounding, the signal passes through a smooth logarithmic compressor that stretches tiny quiet values and squeezes loud peaks.
- At the receiver, the exact inverse expander restores the original dynamics. Effectively, step sizes become tiny near zero and wider near the peaks, keeping the relative signal-to-noise ratio nearly flat across both soft whispers and loud shouts. This exact trick still appears inside modern neural speech codecs and generative audio models that we will explore in Chapter 10.
Take-Home¶
- Signals unify physical and digital worlds, representing continuous functions \(x(t)\) or discrete sequences \(x[n]\) across audio, brainwaves, radar, geophysics, and finance.
- Complex exponentials \(e^{j\omega t}\) act as rotating phasors, turning awkward trigonometric time shifts into simple complex multiplications and explaining negative frequencies as counter-rotating arrows.
- Energy, power, RMS, and decibels quantify signal strength across transient bursts and continuous streams, compressing trillion-fold physical ranges via \(10\log_{10}(P/P_0)\) and \(20\log_{10}(A/A_0)\).
- The Nyquist-Shannon theorem requires \(f_s > 2 f_{\max}\), and without an analogue anti-aliasing low-pass filter beforehand, higher frequencies fold irreversibly into false low-frequency aliases.
- Uniform \(B\)-bit quantisation injects rounding noise of variance \(\Delta^2/12\), yielding the \(6.02B + 1.76\,\text{dB}\) SQNR rule, while non-uniform \(\mu\)-law companding protects quiet passages with finer steps near zero.
Coding Tasks (use CoLab or notebook)¶
-
Visualise Euler's rotating complex phasor \(e^{j\omega t}\) alongside its real cosine shadow, and simulate Nyquist aliasing by sampling a \(13\,\text{Hz}\) sinusoid at \(f_s = 16\,\text{Hz}\) (watching it masquerade identically as a \(3\,\text{Hz}\) wave).
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Part 1: Rotating phasor e^(j * w * t) over one full cycle t_phasor = jnp.linspace(0.0, 1.0, 200) w = 2.0 * jnp.pi * 1.0 z = jnp.exp(1j * w * t_phasor) # Part 2: Aliasing a 13 Hz true tone sampled at fs = 16 Hz (Nyquist = 8 Hz) f_true = 13.0 fs = 16.0 f_alias = abs(f_true - fs) # 3.0 Hz impostor t_dense = jnp.linspace(0.0, 1.0, 1000) n_idx = jnp.arange(0, int(fs) + 1) t_samp = n_idx / fs x_true_dense = jnp.cos(2.0 * jnp.pi * f_true * t_dense) x_alias_dense = jnp.cos(2.0 * jnp.pi * f_alias * t_dense) x_samples = jnp.cos(2.0 * jnp.pi * f_true * t_samp) x_alias_samples = jnp.cos(2.0 * jnp.pi * f_alias * t_samp) max_diff = float(jnp.max(jnp.abs(x_samples - x_alias_samples))) print(f"True frequency: {f_true:.1f} Hz | Sampling rate: {fs:.1f} Hz | Alias: {f_alias:.1f} Hz") print(f"Max difference at sample instants between 13 Hz and 3 Hz: {max_diff:.2e}") fig, axes = plt.subplots(1, 2, figsize=(11.5, 4.2)) # Left plot: Complex unit circle phasor axes[0].plot(jnp.real(z), jnp.imag(z), color="#3498db", lw=1.8, label="Unit circle e^(j w t)") for frac, col in [(0.12, "#9b59b6"), (0.35, "#27ae60"), (0.72, "#f39c12")]: pt = jnp.exp(1j * 2.0 * jnp.pi * frac) axes[0].arrow(0, 0, float(jnp.real(pt)) * 0.92, float(jnp.imag(pt)) * 0.92, head_width=0.05, color=col, lw=2) axes[0].axhline(0, color="#999", lw=0.8) axes[0].axvline(0, color="#999", lw=0.8) axes[0].set_aspect("equal") axes[0].set_xlim(-1.25, 1.25) axes[0].set_ylim(-1.25, 1.25) axes[0].set_xlabel("Real part cos(w t)") axes[0].set_ylabel("Imaginary part sin(w t)") axes[0].set_title("Complex Phasors Rotating Around the Unit Circle") axes[0].grid(alpha=0.3) # Right plot: Aliasing demonstration axes[1].plot(t_dense, x_true_dense, color="#95a5a6", lw=1.2, ls="--", label="True 13 Hz wave") axes[1].plot(t_dense, x_alias_dense, color="#e74c3c", lw=2.2, label="Aliased 3 Hz impostor") axes[1].stem(t_samp, x_samples, linefmt="#3498db", markerfmt="o", basefmt=" ", label="Samples at fs=16 Hz") axes[1].set_xlabel("Time (seconds)") axes[1].set_ylabel("Amplitude") axes[1].set_title("Aliasing Under fs = 16 Hz (Nyquist = 8 Hz)") axes[1].legend(loc="upper right", fontsize=8.5) axes[1].grid(alpha=0.3) plt.tight_layout() plt.show() -
Sweep uniform quantisation bit depth \(B\) from \(3\) to \(16\) bits on a full-scale sine wave, compare the measured quantisation noise variance against the theoretical \(\Delta^2 / 12\) prediction, and verify the \(6.02B + 1.76\,\text{dB}\) SQNR rule.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Full-scale sinusoid (incommensurate frequency so rounding error stays uncorrelated) N = 4096 n = jnp.arange(N, dtype=jnp.float32) x = jnp.sin(2.0 * jnp.pi * 137.0 * n / N) sig_power = float(jnp.mean(x ** 2)) bit_depths = [3, 4, 6, 8, 10, 12, 16] emp_sqnr = [] theo_sqnr = [] var_ratios = [] for B in bit_depths: delta = 2.0 / (2.0 ** B) # Mid-tread uniform quantiser clipped to [-1, 1] xq = jnp.clip(jnp.round(x / delta) * delta, -1.0, 1.0 - delta) err = xq - x noise_power = float(jnp.mean(err ** 2)) theo_var = (delta ** 2) / 12.0 var_ratios.append(noise_power / theo_var) emp_db = 10.0 * float(jnp.log10(sig_power / (noise_power + 1e-20))) theo_db = 6.0206 * B + 1.7609 emp_sqnr.append(emp_db) theo_sqnr.append(theo_db) print(f"B={B:2d} bits | Empirical SQNR: {emp_db:6.2f} dB | Theory: {theo_db:6.2f} dB | Var / (Delta^2/12): {noise_power/theo_var:.3f}") fig, axes = plt.subplots(1, 2, figsize=(11.5, 4.0)) axes[0].plot(bit_depths, theo_sqnr, "--", color="#9b59b6", lw=2.2, label="Theory: 6.02B + 1.76 dB") axes[0].plot(bit_depths, emp_sqnr, "o", color="#27ae60", ms=7, label="Measured Uniform Quantiser") axes[0].set_xlabel("Bit Depth B") axes[0].set_ylabel("SQNR (dB)") axes[0].set_title("Verification of the 6.02 dB per Bit Law") axes[0].legend() axes[0].grid(alpha=0.3) # Show staircase error on a 3-bit quantised wave snippet delta3 = 2.0 / (2.0 ** 3) t_sub = jnp.linspace(0.0, 1.0, 300) s_sub = jnp.sin(2.0 * jnp.pi * t_sub) sq_sub = jnp.round(s_sub / delta3) * delta3 axes[1].plot(t_sub, s_sub, color="#3498db", lw=1.8, label="Original Analogue Wave") axes[1].step(t_sub, sq_sub, where="mid", color="#e74c3c", lw=1.8, label="3-Bit Quantised Wave") axes[1].plot(t_sub, sq_sub - s_sub, color="#f39c12", lw=1.2, alpha=0.85, label="Rounding Error e[n]") axes[1].set_xlabel("Cycle Fraction") axes[1].set_ylabel("Amplitude") axes[1].set_title("3-Bit Quantisation Staircase and Error") axes[1].legend(fontsize=8) axes[1].grid(alpha=0.3) plt.tight_layout() plt.show() -
Compare uniform 6-bit quantisation against \(\mu\)-law non-uniform companding (\(\mu = 255\)) across a wide sweep of input amplitudes (from faint whispers at \(-45\,\text{dB}\) up to full-scale speech at \(0\,\text{dB}\)) and plot the resulting SQNR curve.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt def quantise_uniform(x, bits): delta = 2.0 / (2.0 ** bits) return jnp.clip(jnp.round(x / delta) * delta, -1.0, 1.0 - delta) def quantise_mulaw(x, bits, mu=255.0): # Compress -> Uniform quantise -> Expand y = jnp.sign(x) * jnp.log(1.0 + mu * jnp.abs(x)) / jnp.log(1.0 + mu) yq = quantise_uniform(y, bits) x_hat = jnp.sign(yq) * ((1.0 + mu) ** jnp.abs(yq) - 1.0) / mu return x_hat N = 4096 n = jnp.arange(N, dtype=jnp.float32) base_wave = jnp.sin(2.0 * jnp.pi * 113.0 * n / N) amps_db = jnp.linspace(-45.0, 0.0, 30) bits = 6 sqnr_unif = [] sqnr_mulaw = [] for db in amps_db: amp = 10.0 ** (float(db) / 20.0) x = amp * base_wave p_sig = float(jnp.mean(x ** 2)) err_u = quantise_uniform(x, bits) - x err_m = quantise_mulaw(x, bits, mu=255.0) - x sqnr_unif.append(10.0 * float(jnp.log10(p_sig / (float(jnp.mean(err_u ** 2)) + 1e-16)))) sqnr_mulaw.append(10.0 * float(jnp.log10(p_sig / (float(jnp.mean(err_m ** 2)) + 1e-16)))) print(f"At -35 dB quiet speech (6-bit) | Uniform SQNR: {sqnr_unif[6]:.1f} dB | mu-law SQNR: {sqnr_mulaw[6]:.1f} dB") print(f"At 0 dB full scale (6-bit) | Uniform SQNR: {sqnr_unif[-1]:.1f} dB | mu-law SQNR: {sqnr_mulaw[-1]:.1f} dB") fig, ax = plt.subplots(figsize=(7.5, 4.2)) ax.plot(amps_db, sqnr_unif, "o-", color="#e74c3c", lw=2, ms=4, label="Uniform 6-Bit Quantiser") ax.plot(amps_db, sqnr_mulaw, "s-", color="#27ae60", lw=2, ms=4, label="mu-Law Companded 6-Bit (mu=255)") ax.set_xlabel("Input Signal Level Relative to Full Scale (dB)") ax.set_ylabel("Measured SQNR (dB)") ax.set_title("Non-Uniform Companding Protects Quiet Signals From Rounding Noise") ax.legend() ax.grid(alpha=0.3) plt.tight_layout() plt.show()