8. IIR Filters and Denormals

PySDR’s Filters chapter introduces IIR filters in a few sentences and then deliberately sets them aside: “We will stick with FIR filters in this textbook.” IIR filters still show up in three places. The first is the one-liner every programmer has written, x = x*0.99 + new_value*0.01, which PySDR identifies as a low-pass IIR filter with the remark “Values never fully go away!”. The second is the comparison of a 50-tap FIR with a 12-pole IIR that does the same job. The third is the FM de-emphasis filter in the RDS chapter, designed with scipy.signal.bilinear and run with lfilter.

This chapter takes those three places in order. Each of them hides a floating-point effect that only matters once the filter runs for a long time, in a real program. PySDR’s remark about values that never go away turns out to be literally true, in a way that has cost audio and SDR programs real CPU time. A filter that is perfectly stable on paper becomes unstable when its coefficients are stored as float. And the design itself, the bilinear transform PySDR calls from SciPy, can be done by the compiler.

The code is in code/include/cppsdr/iir.hpp, tested against SciPy in code/tests/test_iir.cpp (reference data from figure-generating-scripts/iir_reference.py) and against GNU Radio’s iir_filter in code/gnuradio_block/test_gr_crosscheck.cc.

Feedback Cannot Be Vectorized in Time

First, why IIR filters need a different implementation strategy from the FIR filters of FIR Filters in C++. An FIR output is a dot product of past inputs, and all outputs can be computed independently, which is why the compiler could vectorize the FIR so well. An IIR output depends on the previous outputs:

\[y[n] = b_0 x[n] + b_1 x[n-1] + b_2 x[n-2] - a_1 y[n-1] - a_2 y[n-2]\]

which reads: the new output is a weighted sum of recent inputs minus a weighted sum of the outputs we just computed. Output \(n\) cannot start before output \(n-1\) is finished. So an IIR filter on one signal runs at the latency of a multiply-add chain, not at the throughput of the SIMD units. This is the price of its efficiency: PySDR’s 12-pole filter needs far fewer operations than the 50-tap FIR, but they cannot be done side by side.

What can be done side by side is many filters: one per channel, per beam, or per FFT bin. GNU Radio’s logpwrfft (see The FFT and the Spectrogram) runs one one-pole filter per frequency bin, and those are independent, so a loop over bins vectorizes perfectly. It is the same trick as running eight Costas loops in parallel in Feedback Loops: the Costas Loop: vectorize across independent recursions, never along one.

“Values Never Fully Go Away”

PySDR’s one-liner is an exponential moving average, and GNU Radio has it as gr::filter::single_pole_iir. In C++ it is a struct with one line of logic:

template <class T>
struct ema {
    T alpha;
    T y{};
    constexpr T process(T x) { return y = alpha * x + (T(1) - alpha) * y; }
};

Now feed it a 1 and then zeros, as happens to every filter when a signal stops or a squelch closes. Mathematically the state is \(0.99^n\), which approaches zero and never reaches it: PySDR’s “values never fully go away”. In floating point the story ends differently, and the test measures how:

log2 of the filter state over time for float, double and float with flush-to-zero; float and double stop at a subnormal value, flush-to-zero reaches exactly zero

The state falls by a constant factor per step, a straight line on this logarithmic axis, until it enters the gray band. Those are the subnormal (or denormal) numbers, the values below the smallest normal float, \(2^{-126}\). They exist so that numbers can shrink gradually toward zero, at the cost of precision: a subnormal float has fewer significant bits the smaller it is. At the bottom of that range something curious happens. When the state is \(k \cdot 2^{-149}\) for a small integer \(k\), the exact product \(0.99 k \cdot 2^{-149}\) must be rounded to a multiple of \(2^{-149}\), and for \(k \le 50\) the nearest multiple is \(k\) itself. The state stops at \(50 \cdot 2^{-149} \approx 7 \cdot 10^{-44}\) after 9877 steps and stays there forever. In double precision the same happens after 73 672 steps, also inside the subnormal range. PySDR’s remark is literally true: the value never goes away, and it ends up as a subnormal number.

Why care about a number that small? On many x86 processors, an operation whose input or result is subnormal is not handled by the fast floating-point hardware but by a microcode “assist”, which costs on the order of a hundred cycles instead of a few. Wittmann et al. measured denormal operations on several Intel and AMD generations to be about two orders of magnitude slower (“Short Note on Costs of Floating Point Operations on current x86-64 Architectures”, arXiv:1506.03997, 2015), and Agner Fog’s instruction tables carry the same warning. A filter whose input has gone quiet then becomes the most expensive code in the program, at the moment nothing is happening. Audio programmers know this problem well, because audio is full of decaying recursions: reverb tails, filters after a note ends, and envelope detectors like the two-time-constant RC simulator in Pirkle’s Designing Audio Effect Plugins in C++ (chapter 13), which is our ema with a different alpha for rising and falling input. JUCE, the most widely used C++ audio framework, provides a ScopedNoDenormals guard for this reason.

The Apple M1 that this book’s measurements run on is not one of those processors. A loop of multiplications on subnormal floats ran at the same 0.17 ns per operation as on normal ones. The stuck subnormal state is still there; it just costs nothing on this machine. Code that will also run on x86 should not rely on that.

The remedy is a CPU mode, not a code change. Flush-to-zero (FTZ) makes the hardware return zero instead of a subnormal result; on x86 a second bit, denormals-are-zero (DAZ), also treats subnormal inputs as zero. With FTZ, the dashed curve above drops from the last normal value straight to exactly 0, after 8690 steps. The mode lives in a per-thread control register (MXCSR on x86, FPCR on ARM), so it is a resource with a scope, and C++ has a pattern for that:

class scoped_flush_to_zero {
public:
    scoped_flush_to_zero()
    {
#if defined(__aarch64__)
        asm volatile("mrs %0, fpcr" : "=r"(saved_));
        asm volatile("msr fpcr, %0" ::"r"(saved_ | (std::uint64_t{1} << 24)) : "memory");   // FPCR.FZ
#elif defined(__x86_64__) || defined(_M_X64)
        saved_ = _mm_getcsr();
        _mm_setcsr(unsigned(saved_) | 0x8040);                                              // FTZ | DAZ
#endif
    }
    ~scoped_flush_to_zero() { /* restore saved_ */ }
    ...
};

void dsp_thread()
{
    cppsdr::iir::scoped_flush_to_zero ftz;   // once, for the whole thread
    while (running) { ... }
}

One lesson from writing the figure’s program belongs here. The first version put the guard around a single process() call inside the loop, and the “float without FTZ” curve came out flushed as well. The optimizer does not know that floating-point arithmetic depends on the control register, so it is free to move an addition or multiplication across the register write. The "memory" clobber orders memory accesses, not arithmetic in registers. The guard is reliable at a coarse scope (a thread, a whole processing call), which is where it belongs anyway. Also note what FTZ is not: it is not -ffast-math. With GCC on x86, linking with that flag also switches FTZ on at program start, but the flag changes far more, as Samples in Memory discussed.

Is FTZ always right? For a receiver, a filter state of \(10^{-38}\) is far below any noise floor, so flushing it costs nothing. But it is a global, per-thread change to arithmetic, and a library should not set it behind the caller’s back; that is why the guard is a separate object the application chooses to create. JUCE’s filter classes also offer a narrower alternative, snapToZero(), which sets the state of one filter to zero when it falls below a threshold.

A Stable Filter That Becomes Unstable

PySDR’s FIR-versus-IIR figure uses a 12-pole IIR filter. How would we write one? scipy.signal.butter(N, Wn) returns it by default as one big fraction \(b(z)/a(z)\) of order \(N\), the direct form, and lfilter(b, a, x) runs it. Take an 8th-order Butterworth low-pass with a cutoff at 2.5 % of the sample rate, a very ordinary filter for an SDR (butter(8, 0.05)). In double precision all eight poles lie inside the unit circle, the largest at radius 0.970, so the filter is stable. Now store the same coefficients as float. Each coefficient changes by less than one part in ten million, yet the largest pole moves to radius 1.022, outside the unit circle. The filter is unstable, and in the test its output overflows to infinity within the 20 000-sample test signal.

How can such a tiny change move a pole that far? The denominator’s coefficients are large numbers that nearly cancel (\(a_4 = 46.2\), \(a_3 = -40.9\), and so on), and the roots of such a polynomial are extremely sensitive to the coefficients, all the more when the poles crowd together near \(z = 1\), which is exactly where a low cutoff puts them.

The standard remedy is to never multiply the filter out: keep it as a cascade of second-order sections (“biquads”), each with only two poles. A biquad’s coefficients are of order 1, and rounding them barely moves its poles. This is what butter(..., output='sos') and sosfilt do, and what Pirkle’s plugin filters are built from (Designing Audio Effect Plugins in C++, chapters 10 and 11).

The C++ design builds the sections directly, at compile time. A Butterworth filter’s analog poles lie evenly spaced on a half circle; the bilinear transform maps each to the \(z\)-plane after “pre-warping” the cutoff with a tangent; each conjugate pair becomes one biquad with its zeros at \(z = -1\):

template <std::size_t N>
constexpr std::array<biquad_coeffs, N / 2> butterworth_lowpass(double fc)   // fc as a fraction of fs
{
    const double wc = 2 * cx::sin(cx::pi * fc) / cx::cos(cx::pi * fc);     // pre-warped: 2 tan(pi fc)
    for (std::size_t k = 0; k < N / 2; ++k) {
        const double theta = cx::pi * double(2 * k + N + 1) / double(2 * N);   // analog pole angle
        // pole s = wc * exp(j theta)  ->  z = (2 + s) / (2 - s)  ->  biquad (1 + z^-1)^2 / (1 + a1 z^-1 + a2 z^-2)
        ...
    }
}
constexpr auto bw8 = butterworth_lowpass<8>(0.025);

Multiplying the four sections back together gives SciPy’s butter(8, 0.05) coefficients to \(4 \cdot 10^{-15}\), and the cascade’s output matches sosfilt to \(10^{-14}\).

Because the coefficients are compile-time constants, so is the answer to “is this filter stable?”. For a biquad, the condition is the “stability triangle”, \(|a_2| < 1\) and \(|a_1| < 1 + a_2\). For a denominator of any order there is the Schur-Cohn step-down test, the Levinson recursion run backwards: repeatedly peel off the highest coefficient as a reflection coefficient \(k\) and reduce the order by one; the polynomial is stable exactly when every \(|k| < 1\). It needs no root finding, only a dozen lines of constexpr code, and it lets the test state the whole story above as compile-time facts:

constexpr auto tf8 = to_direct_form(bw8);
static_assert(is_stable(tf8.a), "the direct form is stable in double precision ...");
static_assert(!is_stable(to_float(tf8.a)), "... and UNSTABLE once its coefficients are rounded to float");
static_assert(is_stable(to_float(std::array<double, 3>{1, bw8[0].a1, bw8[0].a2})),
              "while each biquad survives the rounding");

If a design change ever produces an unstable filter for the type it will run in, the build fails.

GNU Radio’s answer to the same problem is visible in a type name. Its IIR kernel is a template with four types, gr::filter::kernel::iir_filter<i_type, o_type, tap_type, acc_type>, and the float block is iir_filter_ffd: float in, float out, double taps. With double coefficients, the 8th-order direct form above is still stable, and the test confirms that it then matches SciPy’s sosfilt output to \(10^{-8}\). Double taps buy a margin; sections remove the problem. Our classes follow GNU Radio in making the arithmetic type a template parameter (cascade<float, 4>, direct_form<double, 9>), so the choice is visible where the filter is declared.

PySDR’s De-emphasis at Compile Time

The FM receiver in PySDR’s RDS chapter ends with a de-emphasis filter, the inverse of the treble boost every FM transmitter applies:

# De-emphasis filter, H(s) = 1/(RC*s + 1), implemented as IIR via bilinear transform
bz, az = bilinear(1, [75e-6, 1], fs=sample_rate)
x = lfilter(bz, az, x)

The bilinear transform replaces \(s\) by \(2 f_s \frac{z-1}{z+1}\). For this first-order filter the result fits on one line, and it is a constant expression:

constexpr first_order_coeffs deemphasis(double tau, double fs)
{
    const double k = 2 * fs * tau;
    return {1 / (1 + k), 1 / (1 + k), (1 - k) / (1 + k)};   // b0, b1, a1
}
constexpr auto de = deemphasis(75e-6, 250e3);

The coefficients agree with scipy.signal.bilinear to the last bit (difference below \(10^{-15}\)), first_order<double> reproduces lfilter to \(3 \cdot 10^{-16}\), and the same filter run through GNU Radio’s iir_filter<float, float, double, double> agrees to float precision. One detail of GNU Radio’s interface is worth knowing. Its constructor takes the feedback taps in SciPy’s sign convention only when you pass oldstyle = false; the default, true, uses the older convention in which they are added, so SciPy’s a would have to be negated. The cross-check passes false explicitly.

PySDR’s RDS chapter applies this filter at 250 kHz and then decimates by 6 with x[::6], without an anti-aliasing filter. The de-emphasis is a gentle first-order low-pass, so the stereo and RDS subcarriers above 15 kHz are only attenuated, not removed, before they fold into the audio band. A Complete Receiver builds that chain in C++ and decimates with a proper filter.

Key Takeaways

  • An IIR filter is a recursion: it cannot be vectorized along time, only across independent channels.

  • A decaying IIR state does not reach zero in floating point: x = 0.99*x sticks at \(50 \cdot 2^{-149}\) in float, a subnormal, forever. On many x86 CPUs, subnormal arithmetic is about 100 times slower; on the Apple M1 it costs nothing extra.

  • Flush-to-zero is per thread: set it once, at the top of the real-time thread, with an RAII guard. The optimizer does not see the control register, so narrow guards are unreliable.

  • Never run a high-order IIR filter as one direct-form polynomial in float: an ordinary 8th-order Butterworth becomes unstable. Use biquad cascades; GNU Radio’s iir_filter_ffd uses double taps for the same reason.

  • Filter design (bilinear transform, Butterworth poles) and stability tests (stability triangle, Schur-Cohn) are constexpr: the build fails if a filter is unstable in the type it runs in.