Lesson 3 of 15

Quantization

Quantization

After sampling, the continuous amplitude values must be represented by a finite set of discrete levels — this is quantization. The number of bits nn determines how many levels are available:

levels=2n\text{levels} = 2^n

Uniform Quantization

For a signal normalized to [1,1][-1, 1], the step size is:

Δ=22n\Delta = \frac{2}{2^n}

The quantized value maps input xx to the midpoint of its quantization bin:

xq=((x+1)/Δ+0.5)Δ1x_q = \left(\lfloor (x+1) / \Delta \rfloor + 0.5\right) \cdot \Delta - 1

Values outside [1,1][-1, 1] are clamped.

Quantization SNR

The theoretical signal-to-noise ratio for nn-bit quantization is:

SNRdB=6.02n+1.76dB\text{SNR}_{\text{dB}} = 6.02 n + 1.76 \quad \text{dB}

Each additional bit adds roughly 6 dB of dynamic range. A 16-bit audio CD achieves 98\approx 98 dB SNR.

Example

With n=2n = 2 bits (44 levels, Δ=0.5\Delta = 0.5):

  • Input 0.00.0 \to bin index 2.0/0.5=4\lfloor 2.0 / 0.5 \rfloor = 4, clamped to 33... Actually bin 1.0/0.5=2\lfloor 1.0 / 0.5 \rfloor = 2, midpoint (2.5)0.51=0.25(2.5)\cdot 0.5 - 1 = 0.25

Your Task

Implement:

  • quantize(x, n_bits) — clamp xx to [1,1][-1,1], quantize to 2n_bits2^{n\_bits} levels, return midpoint of bin
  • quantization_snr_db(n_bits) — returns 6.02n+1.766.02 n + 1.76
import math

def quantize(x, n_bits):
    x = max(-1.0, min(1.0, x))
    levels = 2 ** n_bits
    step = 2.0 / levels
    q = math.floor((x + 1.0) / step)
    q = min(q, levels - 1)
    return (q + 0.5) * step - 1.0

def quantization_snr_db(n_bits):
    return 6.02 * n_bits + 1.76

print(quantize(0.0, 2))                    # 0.25
print(round(quantization_snr_db(8), 4))    # 49.92
Python runtime loading...
Loading...
Click "Run" to execute your code.