5. Noise, Random Numbers and Statistics

PySDR’s Noise and dB chapter is built on one function, np.random.randn. With it the chapter generates Gaussian noise, makes it complex with (randn + 1j*randn)/np.sqrt(2), scales it to a chosen SNR, and estimates its power with np.var. In C++ each of those steps involves a choice that NumPy makes for you. Which generator, and will it produce the same numbers on another compiler? How do you set the noise power so that the SNR cannot be confused with a power? How do you estimate a variance while samples stream past, when the signal has a DC offset? And how do several threads draw random numbers without sharing a generator?

This chapter answers those questions with small, tested pieces of code, and looks at how GNU Radio answers them. One of GNU Radio’s answers turns out to contain a bug.

The code is in code/include/cppsdr/noise.hpp and code/tests/test_noise.cpp.

Engines Are Specified, Distributions Are Not

C++’s <random> splits a random number generator into two parts. An engine produces uniformly distributed integers (std::mt19937, the Mersenne Twister, is the usual one). A distribution turns them into values with the shape you want (std::normal_distribution, std::uniform_real_distribution). The split matters for reproducibility, because the standard treats the two halves differently.

The engines are completely specified. The standard even states the 10 000th output of a default-seeded std::mt19937 (it is 4123659995), so every conforming library must produce the same sequence, and the test checks that.

The distributions are not. The standard specifies what distribution the numbers must follow, not the algorithm that produces them. Here are the first four values of std::normal_distribution<float> with std::mt19937(42), built once with Clang and Apple’s libc++ and once with GCC 16 and libstdc++, on the same machine:

libc++:     -0.516964   1.221921   0.721333   0.869636
libstdc++:   1.221921  -0.516964   0.869636   0.721333

Both libraries use the same algorithm, Marsaglia’s polar method, which produces Gaussian values in pairs, but they hand out each pair in the opposite order. A simulation seeded with 42 gives different noise depending on which standard library it was compiled against. For an exploratory plot this does not matter. For a test that compares against stored reference values, or a bug report that someone else must reproduce, it does.

The remedy is to keep the specified engine and own the distribution. noise::gaussian is Marsaglia’s polar method written out (the method GNU Radio’s gr::random::gasdev also uses), on uniform numbers taken from the top 53 bits of a 64-bit engine, with each pair always returned in the same order:

double operator()()
{
    if (have_) { have_ = false; return stored_; }
    double u, v, s;
    do {
        u = 2 * uniform() - 1;                 // uniform(): (engine() >> 11) * 2^-53
        v = 2 * uniform() - 1;
        s = u * u + v * v;
    } while (s >= 1 || s == 0);                // a point inside the unit circle
    const double f = std::sqrt(-2 * std::log(s) / s);
    stored_ = v * f;
    have_ = true;
    return u * f;
}

The test pins its first four values for seed 1 to the last bit, and the same test passes with both compilers. One caveat remains: the standard does not require std::log to be correctly rounded, so on a different C math library the last bit could still differ in rare cases. Both builds here use Apple’s math library, so they test the C++ side, not that. It costs about 12 ns per value on the M1, the same as std::normal_distribution<double> with std::mt19937_64.

Complex Noise with a Typed SNR

PySDR’s recipe for complex noise of unit power is (np.random.randn(N) + 1j*np.random.randn(N))/np.sqrt(2): two independent Gaussians, each carrying half of the power. To get a particular SNR, the chapter suggests keeping the signal at unit power and scaling the noise to \(-\mathrm{SNR}\) dB. That is two conversions (dB to linear, total power to per-component standard deviation) that are easy to get wrong by a factor of two or a square root. complex_awgn does both, and takes the SNR as the typed ratio from Decibels with a Dimension: a Link Budget the Compiler Checks:

using namespace cppsdr::units::literals;
noise::complex_awgn n(10.0_dB, /*signal_power=*/1.0, /*seed=*/7);   // noise 10 dB below the signal
std::complex<float> z = n();

// inside: sigma_ = std::sqrt(power / 2), applied to two independent Gaussians

Because the first argument is a units::dB, passing a power in dBW (a different type) does not compile. The test draws a million samples and checks the result: power 0.0998 for a target of 0.1, the two components 0.0499 each, and a correlation between them of 0.001.

Power as a Stream: Welford’s Method

PySDR estimates the power of a zero-mean signal with np.var(x). A receiver needs the same estimate continuously, as samples arrive, for automatic gain control, squelch, or the CFAR detector of CFAR and Real-Time Packet Detection. The obvious streaming form keeps two sums and computes \(E[x^2] - E[x]^2\) at the end. It is also numerically treacherous. Real SDR samples often carry a DC offset, so \(E[x^2]\) and \(E[x]^2\) are large, nearly equal numbers, and their difference is the small variance we want. The test feeds a million float samples of a DC level of 1000 plus unit-variance noise:

method (float)

variance

\(E[x^2] - E[x]^2\) from running sums

\(-24\,760\) (should be 1)

Welford

1.0014

reference (double)

1.0018

The naive result is not merely inaccurate, it is negative: the two sums have rounded so much (a float sum near \(10^9\) steps in units of 64) that their difference is meaningless. Welford’s method (B. P. Welford, Technometrics, 1962) avoids both problems by updating the mean and the sum of squared deviations from the mean directly:

void push(T x)
{
    ++n_;
    const T d = x - mean_;
    mean_ += d / T(n_);
    m2_ += d * (x - mean_);       // variance = m2_ / n
}

It costs one division per sample and stays accurate in float.

Welford’s statistics have a second useful property: two of them can be merged. Given the count, mean and m2_ of two disjoint parts of the data, a formula by Chan, Golub and LeVeque gives the statistics of the union exactly, without revisiting any sample. That suits threads: each worker keeps its own running_stats, with no shared state and no locks, and the results are combined at the end. The test does this with four threads and checks that the merged result equals a single pass over the same samples to rounding (\(10^{-12}\)).

Random Numbers and Threads

Those four workers need four random number generators. Sharing one would be a data race (generators have state), and protecting it with a mutex would serialize the threads and make the sequence depend on scheduling. Seeding each with seed + thread_id is common but weak, because nearby seeds can produce correlated streams in some generators. The standard library’s tool for this is std::seed_seq, which mixes several integers into a full engine state:

auto worker = [](unsigned id, noise::running_stats<>& out) {
    std::seed_seq seq{2024u, id};      // one independent, reproducible stream per worker
    noise::gaussian<> g(seq);
    for (int i = 0; i < 500'000; ++i) out.push(5.0 + 2.0 * g());
};

Each worker’s stream depends only on the run’s seed and its own index, never on which thread gets scheduled first, so the test gets bit-identical statistics from two runs. (A 2018 thread on the GNU Radio mailing list reports a related problem: the fast noise source is not thread-safe, which makes results non-reproducible when more than one such source is used.)

How GNU Radio Makes Noise

GNU Radio’s noise blocks show the trade-off between quality and speed that a real-time noise source faces. Measured per Gaussian value on the M1:

generator

ns/value

note

std::normal_distribution<float>, std::mt19937

10

implementation-defined order

noise::gaussian (std::mt19937_64, double)

12

specified

gr::random::gasdev() (xoroshiro128+, float)

7

polar method

gr::analog::fastnoise_source_f::sample()

3

table lookup

At 10 ns per value, one core produces about 50 million complex noise samples per second, enough for any simulation at SDR sample rates. GNU Radio’s gr::random is faster because it uses xoroshiro128+, a small and fast generator, and float arithmetic. Its fast noise source goes further. It fills a pool of Gaussian samples once (8192 by default) and then outputs pool entries at random indices, which costs one random integer and one load per sample. The catch is that the output is no longer a sequence of independent values: in a million samples, each of the 8192 values appears about 122 times. For many test flowgraphs that is good enough; for estimating a bit error rate below \(10^{-4}\), it may not be.

The fast noise source also has a sample_unbiased() method, which flips the sign of a pool entry at random to make repeats less obvious. Its complex version in GNU Radio 3.10.12 (the version installed here) contains a copy-and-paste slip in gr-analog/lib/fastnoise_source_impl.cc:

float re = (random_int & (UINT64_C(1) << 23)) ? (-s.real()) : (s.real());
float im = (random_int & (UINT64_C(1) << 42)) ? (-s.real()) : (s.real());   // s.real(), not s.imag()

The imaginary part is built from the real part, so every “complex noise” sample lies on one of the two diagonals of the IQ plane: \(|\mathrm{im}| = |\mathrm{re}|\) exactly. The cross-check program (code/gnuradio_block/test_gr_crosscheck.cc) confirms it: 100 000 of 100 000 samples from sample_unbiased() have equal magnitudes, while the ordinary sample() is fine (0 of 100 000). Inside GNU Radio, the channel models that call sample_unbiased() use the real-valued source, which is not affected; Python code calling it on a complex source is. GNU Radio’s main branch has since fixed it (commit ec1bf153c9, 18 October 2026, “analog: fastnoise_source_c: use imag part in sample_unbiased()”); releases up to 3.10.12 have the slip. The cross-check prints which behaviour the installed version shows.

Key Takeaways

  • <random> engines are specified bit for bit; distributions are not. The same seed gives different Gaussian noise with libc++ and libstdc++. For reproducible test vectors, own the distribution.

  • Make the SNR a typed ratio and let one class do the dB-to-linear and power-to-sigma conversions.

  • Estimate power and variance with Welford’s method: \(E[x^2]-E[x]^2\) fails catastrophically with a DC offset, even giving negative variances in float.

  • Welford statistics merge exactly, so each thread can keep its own; give each thread its own engine, seeded through std::seed_seq.

  • GNU Radio trades independence for speed in its fast noise source (a pool of 8192 values), and its complex sample_unbiased() in 3.10.12 sets \(|\mathrm{im}| = |\mathrm{re}|\).