Module contents
Lesson 17 of 26Core 100 min

Random numbers on a computer: generators and sampling

Monte Carlo, weight initialization and dropout rely on a deterministic generator that imitates randomness. Study classical and modern generators (LCG, Mersenne Twister, PCG and Philox), uniform floats from bits, counter-based generators on GPUs, and algorithms transforming uniforms into distributions: numerical inversion, rejection, Ziggurat, alias and Gumbel-max. Practical seed and stream management for reproducibility is covered in m00.

After this lesson you can

  • Implement an LCG, an xorshift and PCG32 and subject them to simple statistical tests.
  • Explain why counter-based generators are the choice for GPUs and parallel computing.
  • Convert random bits into uniform floats without exact zeros and range integers without modulo bias.
  • Implement numerical inversion, rejection, the polar method and Ziggurat, the alias method and Gumbel-max.
  • Calculate a rejection sampler's acceptance rate and anticipate its collapse in high dimensions.

Before you start

Motivation: three failures that raise no error

Every Monte Carlo run, every weight initialization, every dropout mask and every token generated by a language model comes from the same source: a deterministic function that, from a few bytes of state, produces numbers that appear independent and uniform. When that source fails, it almost never fails with an exception. It fails like this:

  • A backtest that does not repeat. You set np.random.seed(0) at the start of the script, but a library you update calls np.random.shuffle one more time during data loading. From that point all simulated paths differ, backtest metrics change and nothing warns you: there is one global state and anyone can consume it.
  • Eight processes doing the same thing. Your Dataset creates self.rng = np.random.default_rng(0) in __init__. The DataLoader copies the object, with its state, to each of eight workers, and all eight apply exactly the same augmentations in the same order. The model sees eight times less variety than you think.
  • Biased token sampling. You convert random bits to a vocabulary index with x % V, or generate Gumbel noise with -log(-log(u)) and an u that can be exactly 0 or 1. The first systematically favors part of the vocabulary, increasingly so with fewer bits; the second occasionally returns ±∞\pm\infty and forces an arbitrary token.

This lesson opens the box. First, generators: how congruential generators, Mersenne Twister, the xorshift family, PCG and GPU counter-based generators work inside, and how a bad generator is detected. Next, bits to numbers: uniform floats without treacherous zeros and unbiased integers in a range. Finally, sampling algorithms that transform uniforms into any distribution: inversion, rejection, the polar method, Ziggurat, the alias method and the Gumbel-max trick. Practical management of seeds and streams for reproducibility is the subject of generators and streams; here we study their underlying mechanisms.

Inside pseudorandom generators

All designs are variations on the same question: how much complexity to put in TT and how much in GG. Congruential generators and Mersenne Twister put almost everything in TT and use a simple output; PCG uses a simple transition and a mixing output; counter-based generators take the idea to the extreme, with T(s)=s+1T(s) = s + 1 and all complexity in GG.

Congruential generators and their lattice: RANDU

The linear congruential generator (LCG) is xn+1=(axn+c) mod mx_{n+1} = (a x_n + c) \bmod m with un=xn/mu_n = x_n/m. Its period depends on aa, cc and mm in a completely known way. If c≠0c \neq 0, the Hull–Dobell theorem (Knuth, vol. 2, §3.2.1.2) says the period is maximal, mm, if and only if gcd⁡(c,m)=1\gcd(c, m) = 1, a−1a - 1 is divisible by every prime dividing mm, and a−1a - 1 is a multiple of 4 if mm is. If c=0c = 0 and m=2km = 2^k with k≥3k \ge 3, the maximum is 2k−22^{k-2}, attained if and only if a≡3a \equiv 3 or 5(mod8)5 \pmod 8 and the seed is odd.

RANDU, the generator in IBM’s scientific library for System/360 in the 1960s, is the textbook example of what can go wrong:

xn+1=65539 xn mod 231,un=xn/231.x_{n+1} = 65539\, x_n \bmod 2^{31}, \qquad u_n = x_n / 2^{31}.

The multiplier 65539=216+365539 = 2^{16} + 3 was chosen because multiplication by it is a shift and two additions, and 65539≡3(mod8)65539 \equiv 3 \pmod 8, so with an odd seed the period is 2292^{29}. So far, nothing serious. The problem is its square:

a2=(216+3)2=232+6⋅216+9≡6⋅216+9=6(a−3)+9=6a−9(mod231).a^2 = (2^{16} + 3)^2 = 2^{32} + 6\cdot 2^{16} + 9 \equiv 6\cdot 2^{16} + 9 = 6(a - 3) + 9 = 6a - 9 \pmod{2^{31}}.

Since xn+2≡a2xnx_{n+2} \equiv a^2 x_n and xn+1≡axnx_{n+1} \equiv a x_n, it follows that xn+2≡6xn+1−9xn(mod231)x_{n+2} \equiv 6x_{n+1} - 9x_n \pmod{2^{31}}. Dividing by 2312^{31},

un+2−6un+1+9un=k∈Z.u_{n+2} - 6u_{n+1} + 9u_n = k \in \Z.

Each triple of consecutive outputs lies on one of the planes 9u1−6u2+u3=k9u_1 - 6u_2 + u_3 = k. How many? With ui∈(0,1)u_i \in (0, 1), the left side lies strictly between 0−6+0=−60 - 6 + 0 = -6 and 9+0+1=109 + 0 + 1 = 10, so k∈{−5,…,9}k \in \{-5, \dots, 9\}: fifteen parallel planes, with normal (9,−6,1)(9, -6, 1) and separation 1/∥(9,−6,1)∥2=1/118≈0.0921/\norm{(9, -6, 1)}_2 = 1/\sqrt{118} \approx 0.092. A three-dimensional simulation with RANDU does not explore the cube: it explores fifteen sheets, with no point between them.

InteractiveRANDU's 15 planes
Generator
3000
24.0°
22.0°
Angle between the view and the planes with normal (9,−6,1)(9, -6, 1)31.9°
Planes (distinct integer values)15: from −5 to 9
Spacing between planes, 1/1181/\sqrt{118}0.0921
Each point is a triple of consecutive RANDU outputs with seed 1, plotted in the unit cube. From the initial view the cloud appears homogeneous. Rotate the cube by dragging, or press “Rotate”, and find the angle where the cloud splits into sheets; the readout of the angle between the view and planes tells you how close you are. Enable coloring by the integer u3−6u2+9u1u_3 - 6u_2 + 9u_1: each sheet is a color. Then switch to PCG64 (these are exactly the numbers from np.random.default_rng(0)) and repeat the search: there is no special angle.

The unsettling thing about the figure is the initial view: structure appears only from a few directions. That is why RANDU remained in use for years. A one-dimensional uniformity test or correlation between consecutive pairs does not detect it; you will check this in the lab.

RANDU is extreme, but not an exception. Marsaglia (1968) proved that dd-tuples of any congruential generator fall on at most (d! m)1/d(d!\,m)^{1/d} parallel hyperplanes: for m=231m = 2^{31} and d=3d = 3, about 2344. RANDU uses 15 of that maximum. The spectral test of Coveyou and MacPherson, which Knuth makes the central criterion for choosing aa, measures the largest separation between hyperplanes in each dimension; a good multiplier makes it small in all low dimensions at once. But no multiplier eliminates the lattice: with m=231m = 2^{31} the state is too small, and congruential generators modulo 2k2^k also have low bits with short periods (RANDU’s lowest bit is always 1, because all xnx_n are odd).

Linear over the two-element field: xorshift and Mersenne Twister

Another family avoids multiplication. Marsaglia (2003) proposed xorshift generators, which apply shift and XOR operations to the state. The 32-bit one with shifts (13,17,5)(13, 17, 5) is

x ^= (x << 13) & 0xFFFFFFFF
x ^= x >> 17
x ^= (x << 5) & 0xFFFFFFFF

and has period 232−12^{32} - 1: it visits every state except zero. If you view xx as a vector over F232\mathbb{F}_2^{32} (the two-element field, where addition is XOR), each shift is a matrix and each x ^= x << a multiplies by (I+La)(\mat{I} + \mat{L}^a). The entire transition is linear: sn+1=Tsn\vb{s}_{n+1} = \mat{T}\vb{s}_n with T∈F232×32\mat{T} \in \mathbb{F}_2^{32\times 32}. Mersenne Twister (Matsumoto and Nishimura, 1998), the default generator in Python, NumPy’s legacy interface and PyTorch on CPU, is the same idea at scale: 624 32-bit words (19937 useful bits, almost 2.5 KB), period 219937−12^{19937} - 1, a Mersenne prime, and an output that applies a linear bijective transformation to the state, tempering. That linearity has a demonstrable price.

Proof

By the Cayley–Hamilton theorem, p(T)=0p(\mat{T}) = \mat{0}, also over F2\mathbb{F}_2. Then c⊤Tnp(T)s0=0\vb{c}\T\mat{T}^n p(\mat{T})\vb{s}_0 = 0 for every nn. Expanding pp, term Tn+js0\mat{T}^{n+j}\vb{s}_0 is sn+j\vb{s}_{n+j}, leaving bn+k+∑j<kajbn+j=0b_{n+k} + \sum_{j<k} a_j b_{n+j} = 0, which in F2\mathbb{F}_2 is the same as the stated equality.

∎

A truly random bit sequence obeys no short linear recurrence: its linear complexity, the length of the shortest recurrence reproducing the first NN bits, is around N/2N/2. Bits of a linear generator with kk bits of state have linear complexity at most kk, and the Berlekamp–Massey algorithm (1969) finds that recurrence from 2k2k bits. This is TestU01’s LinearComp test, and exactly where Mersenne Twister fails: it passes almost the whole battery but has two clear failures, both in linear complexity, in Crush and BigCrush (L’Ecuyer and Simard, 2007). You will see it in the lab with xorshift32, where k=32k = 32 and 64 bits suffice.

Linearity has another consequence, this time for security. Since tempering is invertible, each 32-bit output of Mersenne Twister reveals a state word, and 624 consecutive outputs determine it entirely: from then on, all future outputs are predictable. No special ingenuity is needed, only linear algebra. We return to this when discussing cryptographic generators.

Modern successors retain the speed of the linear part and break its structure with a nonlinear output. xoshiro256** (Blackman and Vigna, 2021) has 256 bits of linear state, period 2256−12^{256} - 1, and returns a function involving multiplications and rotations of one word, the scrambler **, which destroys the recurrence in output bits.

PCG: a congruential generator with output permutation

PCG (O’Neill, 2014) starts from the opposite observation: the high bits of a congruential generator modulo 2642^{64} are excellent; the low ones are bad. So it uses a 64- or 128-bit congruential transition and an output that uses the state’s high bits to decide how to permute the others. In PCG32 (64-bit state, 32-bit output):

  1. Advance the state: s←6364136223846793005 s+c mod 264s \leftarrow 6364136223846793005\, s + c \bmod 2^{64}, with odd cc.
  2. On the previous state, apply a xorshift ((s >> 18) ^ s) and keep 32 bits, positions 27 through 58.
  3. Rotate those 32 bits by a number of positions given by the state’s highest 5 bits (s >> 59).

The bits deciding rotation have the longest period, so the permutation changes from step to step without a short pattern, and low output bits inherit the quality of high state bits. The result passes BigCrush with 16 bytes of state and one multiplication per number. np.random.default_rng uses PCG64: 128-bit state, XSL RR output (XOR of the two halves and 64-bit rotation), period 21282^{128}. In the lab you implement it from scratch and check that it matches NumPy bit for bit.

Period, equidistribution and test batteries

A “good” generator has properties that can be proved and properties that can only be tested.

  • Period. Necessary but cheap: a period of 2642^{64} suffices for any reasonable use in a single stream. Astronomical periods (219937−12^{19937} - 1) do not buy statistical quality by themselves.
  • Equidistribution. A generator with ww-bit outputs is kk-distributed to tt bits of accuracy if, over its complete period, each of the 2kt2^{kt} cells formed by the tt high bits of kk consecutive outputs appears the same number of times (except sometimes the all-zero cell). Mersenne Twister is 623-distributed to 32 bits. This is a structural guarantee about the entire period, not the numbers you will use.
  • Empirical batteries. TestU01 (L’Ecuyer and Simard, 2007) groups dozens of tests into SmallCrush, Crush and BigCrush; PractRand applies increasingly long tests until the generator fails or time runs out. Each test computes a statistic whose distribution is known if the numbers are independent and uniform, and checks whether the observed value is plausible. A generator that reproducibly fails a test (with pp value 10−1510^{-15}, not 0.010.01) has a defect; passing all proves nothing, only that the defect, if any, is not one these tests seek.

Lab: generators from scratch and statistical tests

Start by checking RANDU’s arithmetic: the multiplier’s square, the fifteen integers and Marsaglia’s bound.

[ ]Inside RANDUBrowser
import numpy as np

a, m = 65539, 2**31
print("a² mod 2^31 =", a * a % m, "   6a − 9 =", 6 * a - 9, "   a mod 8 =", a % 8)

def randu(seed, n):
    x, out = seed, np.empty(n, dtype=np.int64)
    for i in range(n):
        x = (a * x) % m
        out[i] = x
    return out

x = randu(1, 30_000)
comb = x[2:] - 6 * x[1:-1] + 9 * x[:-2]          # x_{n+2} − 6x_{n+1} + 9x_n, en enteros exactos
print("restos módulo 2^31:", set((comb % m).tolist()))
print("valores de k:", sorted(set((comb // m).tolist())))
print(f"separación entre planos 1/√118 = {1 / np.sqrt(118):.4f}")
print(f"cota de Marsaglia (3!·2^31)^(1/3) = {(6 * m) ** (1 / 3):.0f} planos")
print("¿todas las salidas impares?", bool(np.all(x % 2 == 1)))

Now the four generators according to their specifications: MINSTD (Park and Miller’s congruential generator, a=16807a = 16807, m=231−1m = 2^{31} - 1), RANDU, xorshift32 and PCG32. For PCG32 the output is checked against O’Neill’s demonstration program (pcg32-demo, seed 42 and sequence 54), which starts with 0xa15c02b7.

[ ]Four generators from scratchBrowser
import numpy as np

M32, M64 = 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF

def lcg(a, c, m, seed, n):
    x, out = seed, np.empty(n)
    for i in range(n):
        x = (a * x + c) % m
        out[i] = x / m
    return out

def xorshift32(seed, n):
    x, out = seed, np.empty(n)
    for i in range(n):
        x ^= (x << 13) & M32
        x ^= x >> 17
        x ^= (x << 5) & M32
        out[i] = x / 2**32
    return out

class PCG32:
    MULT = 6364136223846793005
    def __init__(self, seed, seq):
        self.inc = ((seq << 1) | 1) & M64          # el incremento c tiene que ser impar
        self.state = 0
        self.next()
        self.state = (self.state + seed) & M64
        self.next()
    def next(self):
        old = self.state
        self.state = (old * self.MULT + self.inc) & M64
        xs = (((old >> 18) ^ old) >> 27) & M32     # xorshift y 32 bits del medio
        rot = old >> 59                            # los 5 bits más altos deciden la rotación
        return ((xs >> rot) | (xs << ((-rot) & 31))) & M32
    def floats(self, n):
        return np.array([self.next() for _ in range(n)]) / 2**32
    def float53(self):
        """Flotante de 53 bits con dos salidas de 32: 27 bits altos de una y 26 de otra (como Python)."""
        a, b = self.next() >> 5, self.next() >> 6
        return (a * 2**26 + b) * 2.0**-53

p = PCG32(42, 54)
print("PCG32(42, 54):", [hex(p.next()) for _ in range(3)], "  referencia: 0xa15c02b7 0x7b47f409 0xba1d3330")
q = PCG32(42, 54)
print("flotantes de 53 bits:", [q.float53() for _ in range(2)])

N = 3 * 2**16
muestras = {
    "RANDU": lcg(65539, 0, 2**31, 1, N),
    "MINSTD": lcg(16807, 0, 2**31 - 1, 1, N),
    "xorshift32": xorshift32(2463534242, N),
    "PCG32": PCG32(42, 54).floats(N),
    "PCG64 (NumPy)": np.random.default_rng(0).random(N),
}
print({k: v[:3].round(4).tolist() for k, v in muestras.items()})

float53 is the 53-bit float conversion studied below; for the tests 32-bit resolution, x/232x/2^{32}, suffices because none looks beyond the high 8 bits. The four tests that follow are small versions of TestU01’s. Each returns an pp value: the probability, if numbers really were independent and uniform, of seeing a statistic at least as extreme.

  • One-dimensional chi-square: 64 equal bins in [0,1)[0, 1).
  • Serial correlation: the coefficient between unu_n and un+1u_{n+1}; under independence, N ρ^\sqrt{N}\,\hat\rho is approximately standard normal.
  • Three-dimensional chi-square: disjoint triples (u3i,u3i+1,u3i+2)(u_{3i}, u_{3i+1}, u_{3i+2}) in 10310^3 cells.
  • Birthday spacings (Marsaglia): distribute m=512m = 512 “birthdays” among 2242^{24} “days” (here, 2563256^3 cells formed from triples), sort them and count repeated spacings between consecutive birthdays. Under the null hypothesis that number is approximately Poisson with mean λ=m3/(4⋅224)=2\lambda = m^3/(4 \cdot 2^{24}) = 2; 128 repetitions are summed and compared with a Poisson of mean 256.
[ ]Four statistical testsBrowser
import numpy as np
from scipy import stats

def bateria(u):
    n = len(u)
    p_chi1 = stats.chisquare(np.bincount((u * 64).astype(int), minlength=64)).pvalue
    r = np.corrcoef(u[:-1], u[1:])[0, 1]
    p_corr = 2 * stats.norm.sf(abs(r) * np.sqrt(n))
    tri = u[: n // 3 * 3].reshape(-1, 3)
    c = (tri * 10).astype(int)
    p_chi3 = stats.chisquare(np.bincount(c[:, 0] * 100 + c[:, 1] * 10 + c[:, 2], minlength=1000)).pvalue
    d = (tri * 256).astype(np.int64)
    dias = d[:, 0] * 65536 + d[:, 1] * 256 + d[:, 2]          # 2^24 días
    rep = 0
    for j in range(len(dias) // 512):
        esp = np.sort(np.diff(np.sort(dias[512 * j: 512 * (j + 1)])))
        rep += int(np.sum(esp[1:] == esp[:-1]))
    lam = 2 * (len(dias) // 512)
    p_bday = min(1.0, 2 * min(stats.poisson.cdf(rep, lam), stats.poisson.sf(rep - 1, lam)))
    return p_chi1, p_corr, p_chi3, rep, lam, p_bday

print(f"{'generador':14s} {'χ² 1D':>8s} {'corr.':>8s} {'χ² 3D':>9s} {'cumpleaños':>18s}")
for nombre, u in muestras.items():
    p1, pc, p3, rep, lam, pb = bateria(u)
    print(f"{nombre:14s} {p1:8.3f} {pc:8.3f} {p3:9.1e}   {rep:5d}/{lam} p={pb:.1e}")

The table tells RANDU’s story in numbers. It passes one-dimensional chi-square and serial correlation effortlessly: its marginal values are uniform and consecutive pairs are not linearly correlated. But three-dimensional chi-square gives an pp value on the order of 10−1310^{-13}, and birthday spacings show about 2900 repetitions where 256 are expected: RANDU’s birthdays fall on a regular lattice and their distances repeat much more than by chance. MINSTD, xorshift32 and both PCGs show nothing similar. Notice, however, PCG64’s 0.0090.009 in one-dimensional chi-square and xorshift32’s 0.040.04 in three dimensions: with twenty pp values in the table, one or two falling below 0.050.05 is expected by chance alone. What reveals a defect is not an isolated small pp but an astronomically small one reproducible with another seed.

Passing does not absolve xorshift32. The linear-complexity test sinks it with 64 bits:

[ ]Linear complexity with Berlekamp–MasseyBrowser
import numpy as np

def berlekamp_massey(bits):
    """Longitud de la recurrencia lineal más corta (sobre F2) que genera la sucesión de bits."""
    s = np.array(bits, dtype=np.uint8)
    n = len(s)
    c = np.zeros(n + 1, dtype=np.uint8); b = np.zeros(n + 1, dtype=np.uint8)
    c[0] = b[0] = 1
    L, mm = 0, -1
    for i in range(n):
        d = s[i] ^ (np.dot(c[1:L + 1], s[i - L:i][::-1]) & 1) if L else s[i]
        if d:
            t = c.copy()
            c[i - mm:] ^= b[: n + 1 - (i - mm)]
            if 2 * L <= i:
                L, mm, b = i + 1 - L, i, t
    return L

def bits_bajos(gen_next, n):
    return [gen_next() & 1 for _ in range(n)]

estado = [2463534242]
def xs_next():
    x = estado[0]
    x ^= (x << 13) & 0xFFFFFFFF; x ^= x >> 17; x ^= (x << 5) & 0xFFFFFFFF
    estado[0] = x
    return x

pcg = PCG32(42, 54)
for N in (64, 400):
    print(f"N = {N}:  xorshift32 → {berlekamp_massey(bits_bajos(xs_next, N)):3d}"
          f"   PCG32 → {berlekamp_massey(bits_bajos(pcg.next, N)):3d}   (azar: ≈ N/2 = {N // 2})")

The low bit of xorshift32 obeys a recurrence of order 32, its state dimension, and Berlekamp–Massey finds it with 64 bits; with 400 bits it is still 32. PCG32’s has linear complexity N/2N/2, like a random bit, because state-dependent rotation is nonlinear. For Mersenne Twister the number would be 19937, and about 40000 bits suffice to see it: this is the test it fails in BigCrush.

From bits to numbers

A generator produces bit words. Almost always you need something else: a float in [0,1)[0, 1), an integer in {0,…,n−1}\{0, \dots, n-1\}. Both conversions have pitfalls.

Uniform floats: 53 bits and endpoints

An float64 has a 53-bit significand (floating-point representation). Standard conversion takes the high 53 bits of a 64-bit word and scales them:

u=⌊x/211⌋⋅2−53∈{0, 2−53, 2⋅2−53, …, 1−2−53}.u = \lfloor x / 2^{11} \rfloor \cdot 2^{-53} \in \{0,\ 2^{-53},\ 2\cdot 2^{-53},\ \dots,\ 1 - 2^{-53}\}.

These are 2532^{53} equally spaced values, all exactly representable and equiprobable, with largest 1−2−53<11 - 2^{-53} < 1. This is what NumPy and PCG64 do; Python and Mersenne Twister combine 27 and 26 bits from two 32-bit outputs for the same result. The naive alternative, x / 2**64 in floating point, is worse than it seems: the quotient is rounded to the nearest float, and since near 1 floats are separated by 2−532^{-53}, all x≥264−210x \ge 2^{64} - 2^{10} round to exactly 1.0. Its probability is 2−542^{-54}, small, but it breaks the promise that u<1u < 1 and produces an unexpected value.

The lower endpoint is more dangerous. With standard conversion, u=0u = 0 has probability 2−532^{-53}, and in float32 (24-bit significand) the analogous conversion gives P(u=0)=2−24≈6×10−8\Pr(u = 0) = 2^{-24} \approx 6\times 10^{-8}. One dropout mask over a large batch’s activations, or Gumbel noise for a batch of 2048 sequences over a 50000-token vocabulary, consumes on the order of 10810^8 uniforms: the expected number of exact zeros is around 6. And −log⁡(0)=+∞-\log(0) = +\infty. The solutions are simple:

  • use 1−u∈(0,1]1 - u \in (0, 1] when taking log⁡\log: -np.log1p(-u) instead of -np.log(u);
  • or generate in the open interval, u=(⌊x/211⌋+12) 2−53∈(0,1)u = (\lfloor x/2^{11} \rfloor + \tfrac12)\, 2^{-53} \in (0, 1);
  • or check which interval your library returns: cuRAND’s curand_uniform, for example, returns values in (0,1](0, 1], excluding 0 and including 1 (as its documentation states).
[ ]Interval endpointsBrowser
import numpy as np

# 1. la conversión de NumPy es (x >> 11) * 2^-53 sobre la salida de PCG64
raw = np.random.PCG64(0).random_raw(4)
print("random() == (x >> 11)·2^-53:", np.array_equal(np.random.default_rng(0).random(4), (raw >> np.uint64(11)) * 2.0**-53))

# 2. x / 2^64 en coma flotante: los x más altos se redondean a 1.0
for x in (2**64 - 1025, 2**64 - 1024, 2**64 - 1):
    print(f"x = 2^64 − {2**64 - x:4d}:  x / 2^64 = {float(x) / 2**64!r}")

# 3. convertir un float64 casi 1 a float32 también da 1.0
print("float32(1 − 2^-30) == 1.0:", np.float32(1 - 2.0**-30) == 1.0)

# 4. ceros exactos en float32: P(u = 0) = 2^-24
g = np.random.default_rng(1)
ceros, n = 0, 0
for _ in range(8):
    u = g.random(2**22, dtype=np.float32)
    ceros += int(np.count_nonzero(u == 0)); n += u.size
print(f"{n:,} uniformes float32: {ceros} ceros exactos (esperados {n / 2**24:.1f})")
with np.errstate(divide="ignore"):
    print("−log(0) =", -np.log(np.float32(0.0)), "   −log1p(−0) =", -np.log1p(-np.float32(0.0)))

The cell confirms all three pitfalls: the highest 1024 values of xx give exactly 1.0, rounding to float32 also produces ones, and among 2252^{25} float32 uniforms exact zeros appear (one in this run, when 2 are expected), each an +∞+\infty waiting for a logarithm.

Range integers without modulo bias

To choose an index in {0,…,n−1}\{0, \dots, n - 1\} with a uniform word xx of ww bits, the temptation is x % n. If nn does not divide 2w2^w, remainders are not equiprobable: there are ⌈(2w−r)/n⌉\lceil (2^w - r)/n \rceil values of xx with remainder rr, equal to ⌊2w/n⌋+1\lfloor 2^w/n \rfloor + 1 for r<2w mod nr < 2^w \bmod n and ⌊2w/n⌋\lfloor 2^w/n\rfloor for the rest. With nn small relative to 2w2^w relative bias is at most n/2wn/2^w and usually negligible, but grows with nn. The extreme case is instructive: with w=32w = 32 and n=3⋅230n = 3\cdot 2^{30}, remainders below 2302^{30} are twice as probable as the rest, and the first third of the range occurs half the time instead of one third.

The classic solution is rejection: discard x≥2w−(2w mod n)x \ge 2^w - (2^w \bmod n) and keep x % n. It is correct but performs a division for every number, the most expensive integer operation. Lemire (2019) avoids nearly all divisions with an 2w2w-bit multiplication. This is the method used by NumPy’s Generator.integers (its documentation cites the paper).

Proof

Fix r∈{0,…,n−1}r \in \{0, \dots, n-1\}. The xx with h=rh = r are those satisfying r 2w≤xn<(r+1) 2wr\,2^w \le x n < (r + 1)\,2^w, and for them ℓ=xn−r 2w\ell = xn - r\,2^w. The map x↦ℓx \mapsto \ell is injective, and its image is exactly the set of ℓ∈[0,2w)\ell \in [0, 2^w) with ℓ≡−r 2w(modn)\ell \equiv -r\,2^w \pmod n: given one, x=(ℓ+r 2w)/nx = (\ell + r\,2^w)/n is an integer less than (2w+(n−1)2w)/n=2w(2^w + (n-1)2^w)/n = 2^w. Thus the ℓ\ell of class rr form a residue class modulo nn inside [0,2w)[0, 2^w). Interval [t,2w)[t, 2^w) has length 2w−t=n⌊2w/n⌋2^w - t = n\lfloor 2^w/n \rfloor, a multiple of nn, and therefore contains exactly ⌊2w/n⌋\lfloor 2^w/n \rfloor elements of any residue class. Each rr thus has the same number of accepted xx, ⌊2w/n⌋\lfloor 2^w/n \rfloor. Summing over the nn values of rr, n⌊2w/n⌋=2w−tn\lfloor 2^w/n\rfloor = 2^w - t of the 2w2^w values of xx are accepted, so tt are rejected, with probability t/2wt/2^w, and t<nt < n.

∎

The practical trick is that t<nt < n, so tt (with its division) only needs computing when ℓ<n\ell < n, which happens with probability n/2wn/2^w. Almost always, a range integer costs one multiplication.

[ ]Modulo versus LemireBrowser
import numpy as np
from scipy import stats

g = np.random.default_rng(3)
n = 3 * 2**30
x = (g.bit_generator.random_raw(1_000_000) >> np.uint64(32)).astype(np.uint64)   # palabras de 32 bits

mod = x % np.uint64(n)
print(f"x % n:   fracción en el primer tercio = {np.mean(mod < n // 3):.4f}   (debería ser 0.3333)")

def lemire(xs, n, w=32):
    """Vectorizado: devuelve los h aceptados y cuántos se rechazaron."""
    prod = xs * np.uint64(n)                      # cabe en 64 bits porque x, n < 2^32
    h, l = prod >> np.uint64(w), prod & np.uint64(2**w - 1)
    t = (2**w) % n
    ok = l >= np.uint64(t)
    return h[ok], int(np.count_nonzero(~ok))

h, rech = lemire(x, n)
print(f"Lemire:  fracción en el primer tercio = {np.mean(h < n // 3):.4f},  rechazados {rech / len(x):.4f} (t/2^32 = {2**32 % n / 2**32:.4f})")
tercios = np.bincount((h // (n // 3)).astype(int), minlength=3)
print("chi-cuadrado de los tercios, p =", round(stats.chisquare(tercios).pvalue, 3))
_, r6 = lemire(x, 6)
print("con n = 6, rechazados:", r6, " (t = 2^32 mod 6 =", 2**32 % 6, ")")

Counter-based generators

A GPU has tens of thousands of threads, each needing its own numbers. With a stateful generator there are two poor options: a shared generator (and a queue to use it) or a state per thread (2.5 KB per thread with Mersenne Twister, plus the problem of ensuring streams do not overlap). Salmon, Moraes, Dror and Shaw (2011) proposed changing the design fundamentally.

The consequences are exactly what parallel computing needs:

  • Random access. Number 101210^{12} is computed directly, without generating previous ones: skipping is free.
  • Streams by key. Two distinct keys give two distinct permutations of counter space, unrelated to each other. There is no need to prove two streams do not overlap: they are two different functions evaluated at the same points.
  • Minimal state and reproducibility. Thread jj of a kernel uses gk(desplazamiento+j)g_k(\text{desplazamiento} + j) in its registers; the result does not depend on the number of threads or their execution order.

Philox replaces a cipher’s boxes with integer products. One Philox4x32 round takes four 32-bit words, multiplies two by constants, and combines the high and low halves of the 64-bit products with the other two words and the key using XOR, changing positions; the key is incremented with Weyl constants between rounds. Multiplication is the operation that mixes most per cycle on a GPU. With the standard version’s ten rounds, Philox passes SmallCrush, Crush and BigCrush, as do all Random123 generators according to its documentation. Threefry adapts Threefish, the block cipher of SHA-3 candidate Skein, using addition, rotations and XOR (ARX), and is JAX’s default generator (Threefry-2x32). Random123, which implements both, explicitly warns that they are unsuitable for cryptography: rounds are reduced to the minimum passing statistical tests, not the number resisting an adversary.

Where they are: cuRAND offers Philox4_32_10 alongside XORWOW (its default generator, a xorshift with a Weyl counter), MRG32k3a and MTGP32; PyTorch CUDA kernels use Philox with seed and offset state, so each random operation reserves a counter segment; NumPy offers np.random.Philox (the 4x64 variant).

[ ]Inside PCG64 and Philox, against NumPyBrowser
import numpy as np

M64, M128 = 2**64 - 1, 2**128 - 1

# --- PCG64 (XSL RR): estado de 128 bits, salida de 64
bg = np.random.PCG64(0)
s, inc = bg.state["state"]["state"], bg.state["state"]["inc"]
print(f"estado inicial de default_rng(0): {s:#x}\nincremento:                       {inc:#x}")
MULT = 0x2360ED051FC65DA44385DF649FCCF645
def pcg64_next():
    global s
    s = (s * MULT + inc) & M128                   # paso del congruencial de 128 bits
    v = (s >> 64) ^ (s & M64)                     # XSL: XOR de las dos mitades
    rot = s >> 122                                # RR: rotación según los 6 bits altos
    return ((v >> rot) | (v << ((-rot) & 63))) & M64
mio = [pcg64_next() for _ in range(5)]
print("PCG64 desde cero == NumPy:", mio == [int(v) for v in np.random.PCG64(0).random_raw(5)])

# --- Philox4x64-10: 10 rondas de multiplicaciones de 128 bits
MUL = (0xD2E7470EE14C6C93, 0xCA5A826395121157)
WEYL = (0x9E3779B97F4A7C15, 0xBB67AE8584CAA73B)
def philox4x64(ctr, key, rondas=10):
    c, k = list(ctr), list(key)
    for _ in range(rondas):
        p0, p1 = MUL[0] * c[0], MUL[1] * c[2]
        c = [(p1 >> 64) ^ c[1] ^ k[0], p1 & M64, (p0 >> 64) ^ c[3] ^ k[1], p0 & M64]
        k = [(k[0] + WEYL[0]) & M64, (k[1] + WEYL[1]) & M64]
    return c

ref = [int(v) for v in np.random.Philox(key=7).random_raw(8)]
print("Philox desde cero == NumPy:", philox4x64([1, 0, 0, 0], [7, 0]) + philox4x64([2, 0, 0, 0], [7, 0]) == ref,
      " (NumPy incrementa el contador antes de usarlo)")
# acceso aleatorio: el bloque 10^12, directamente
directo = philox4x64([10**12 + 1, 0, 0, 0], [7, 0])
saltado = np.random.Philox(key=7, counter=[10**12, 0, 0, 0]).random_raw(4)
print("bloque 10^12 sin generar los anteriores:", directo == [int(v) for v in saltado])

Inside parallel streams

With a stateful generator there are two clean ways to distribute streams. The first is skipping: PCG64 advances nn steps in O(log⁡n)\bigO(\log n), because composing congruential generators gives another congruential generator (s↦ans+c (an−1)/(a−1)s \mapsto a^n s + c\,(a^n - 1)/(a - 1), computable by repeated squaring), and jumped() skips about (φ−1) 2128≈2.1×1038(\varphi - 1)\,2^{128} \approx 2.1\times 10^{38} steps; Mersenne Twister has a skip but it is expensive (computed with polynomials over F2\mathbb{F}_2 of degree 19937), and NumPy offers it as MT19937.jumped(), advancing 21282^{128} steps. The second is seeding each stream with a high-quality mix of the root seed and its position in the tree, which is what SeedSequence does.

Seeding with semilla + i mixes two risks. One is bookkeeping: process 1 of an experiment with seed 0 and process 0 of an experiment with seed 1 receive the same seed, and therefore the same stream. The other depends on how the generator converts seed to state. If the conversion is nearly linear, consecutive seeds give consecutive states and related streams (in a congruential generator with x0′=x0+dx_0' = x_0 + d, difference xn′−xn≡and(modm)x_n' - x_n \equiv a^n d \pmod m does not depend on x0x_0, as shown in an exercise in the reproducibility lesson). Mersenne Twister also has its own weakness: from states with many zeros its mixing is slow, and 2002 initialization was redesigned to make those states unlikely. With a counter-based generator the problem does not arise: each process uses its own key, and stream independence is that of permutations gkg_k for different keys.

Pseudorandom versus cryptographic generators

Everything above seeks statistical quality: no reasonable test distinguishes outputs from randomness. A cryptographically secure generator (CSPRNG) promises something much stronger: no efficient algorithm seeing previous outputs can predict the next bit with probability appreciably greater than 1/21/2. Mersenne Twister and congruential generators fail trivially: state is reconstructed from a few outputs (624 for Mersenne Twister, by the linearity just seen) and predicts everything else. PCG is much harder to invert, but is not designed to resist an adversary either, and attacks recovering its state from output have been published. Therefore:

  • Never use random or numpy.random for secrets: session tokens, passwords, keys, reset links or identifiers that must not be guessable.
  • Use Python’s secrets module (PEP 506), which takes bytes from the operating system’s cryptographic generator (os.urandom), or your platform’s CSPRNG.
  • How to detect it: security static analyzers flag it (Bandit, for example, flags uses of random with rule B311), and code review should look for random. in any path generating something an attacker wants to guess.
[ ]secrets: the right way for secretsBrowser
import secrets

token = secrets.token_urlsafe(32)        # 32 bytes del CSPRNG del sistema, en base64 para URL
print("longitud del token:", len(token), "caracteres;  ¿es str?", isinstance(token, str))
print("entero uniforme en [0, 10^6):", 0 <= secrets.randbelow(10**6) < 10**6)
print("comparación en tiempo constante:", secrets.compare_digest("abc", "abc"))

The relationship is asymmetric: a CSPRNG is an excellent PRNG (though slower), but an excellent PRNG is not a CSPRNG. Philox and Threefry, despite their origin in block ciphers, are not either, as their authors warn.

The inverse transform as an algorithm

From here we take the source of uniforms as given and build samplers. You already know the first as a theorem: if FF is a distribution function and F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\} its generalized inverse, then X=F−1(U)X = F^{-1}(U) with U∼Unif⁡(0,1)U \sim \Unif(0, 1) has distribution function FF (the probability integral transform). The key is equivalence F−1(u)≤x  ⟺  u≤F(x)F^{-1}(u) \le x \iff u \le F(x), valid for any right-continuous FF, with jumps or flat segments.

InteractiveThe inverse transform machine
Distribution function FF and latest paths U→F−1(U)U \to F^{-1}(U)
Target density and sample histogram
  • target density
  • histogram of F−1(U)F^{-1}(U)
  • last path
0.6 N(1.6,0.452)+0.4 N(4.2,0.352)0.6\,\Normal(1.6, 0.45^2) + 0.4\,\Normal(4.2, 0.35^2)
Samples nn200
Last U→F−1(U)U \to F^{-1}(U)0.965 → 4.673
Dn=sup⁡x∣Fn(x)−F(x)∣D_n = \sup_x \abs{F_n(x) - F(x)}0.0761
Reference 1.36/n1.36/\sqrt{n} (95%)0.0962
Above, the distribution function FF; each uniform UU starts on the vertical axis, travels horizontally to the curve and drops to the xx axis: that point is F−1(U)F^{-1}(U). Below are the target density and sample histogram. Draw samples and see how DnD_n, the greatest distance between the empirical distribution function and FF, falls as 1/n1/\sqrt n. Try the distribution with a gap: does any UU land on the flat segment? And the mixed one: what happens to UU values hitting the jump? In “Draw your own”, paint your density by dragging on the lower panel.

The figure shows the geometric intuition: the slope of FF determines how many uniforms fall in each region. Where FF is steep (high density), a small interval of xx captures a large interval of uu; where flat, none. Atoms appear as vertical jumps capturing an interval of uu whose length equals their mass.

Closed formulas. Exponential: F(x)=1−e−λxF(x) = 1 - e^{-\lambda x}, F−1(u)=−log⁡(1−u)/λF^{-1}(u) = -\log(1 - u)/\lambda; since 1−U1 - U is also uniform, it is often written −log⁡(U)/λ-\log(U)/\lambda, but that form breaks with U=0U = 0, and -np.log1p(-u) is also exact for small uu. Cauchy: F−1(u)=tan⁡(π(u−12))F^{-1}(u) = \tan(\pi(u - \tfrac12)). Weibull, logistic, Pareto and Gumbel also have explicit inverses.

Numerical inversion. For gamma or normal, FF is evaluated with special functions but F−1F^{-1} has no formula. For each uu, solve F(x)−u=0F(x) - u = 0 with a bracketing method like Brent (secant and Brent): FF is monotone and bracket [a,b][a, b] with F(a)≤u≤F(b)F(a) \le u \le F(b) guarantees convergence. It costs dozens of evaluations of FF per sample: exact but slow.

Tables with interpolation. Evaluate FF once on a grid and invert by linear (or better, polynomial) interpolation of pairs (F(xj),xj)(F(x_j), x_j). Per-sample cost is a binary search, but error depends on the curvature of F−1F^{-1}, which explodes in tails where density is small. Serious implementations, such as NumericalInversePolynomial of scipy.stats.sampling (the PINV method of Derflinger, Hörmann and Leydold, 2010), control error in uu, ∣F(x^)−u∣\abs{F(\hat x) - u}, the natural quantity: if the approximation of F−1F^{-1} is monotone and its error in uu is at most ε\eps, the sample distribution function is at distance at most ε\eps from FF (in Kolmogorov distance, the same as the KS test), even though error in xx in a tail can be much larger.

Lab: inversion

[ ]Inversion: closed form, numerical and tabulatedBrowser
import numpy as np, time
from scipy import stats, optimize, special

g = np.random.default_rng(2024)
u = g.random(100_000)
x_exp = -np.log1p(-u)                            # Exp(1)
x_cau = np.tan(np.pi * (u - 0.5))                # Cauchy estándar
print("KS exponencial p =", round(stats.kstest(x_exp, "expon").pvalue, 4),
      "  KS Cauchy p =", round(stats.kstest(x_cau, "cauchy").pvalue, 4))

# Gamma(2.5): F es la gamma incompleta regularizada; F^{-1} no tiene fórmula cerrada
F = lambda x: special.gammainc(2.5, x)
uu = g.random(2000)
exacta = special.gammaincinv(2.5, uu)            # referencia de SciPy
t0 = time.perf_counter()
x_brent = np.array([optimize.brentq(lambda x: F(x) - ui, 0.0, 60.0, xtol=1e-12) for ui in uu])
t_brent = (time.perf_counter() - t0) / len(uu)
rejilla = np.linspace(0, 30, 4097)
Fr = F(rejilla)
t0 = time.perf_counter()
x_tabla = np.interp(g.random(1_000_000), Fr, rejilla)
t_tabla = (time.perf_counter() - t0) / 1e6
print(f"Brent:  error máx en x {np.max(np.abs(x_brent - exacta)):.1e}, {t_brent * 1e6:.1f} µs por muestra")
err_tabla = np.abs(np.interp(uu, Fr, rejilla) - exacta)
print(f"tabla:  error máx en x {err_tabla.max():.1e}, {t_tabla * 1e9:.0f} ns por muestra"
      f"  (cociente de tiempos ≈ {t_brent / t_tabla:.0f})")
peor = uu[np.argmax(err_tabla)]
print(f"el peor caso de la tabla está en u = {peor:.4f} (una cola)")

from scipy.stats.sampling import NumericalInversePolynomial
pinv = NumericalInversePolynomial(stats.gamma(2.5), random_state=1)
print("PINV: error en u máximo", f"{pinv.u_error().max_error:.1e}",
      "  KS p =", round(stats.kstest(pinv.rvs(100_000), stats.gamma(2.5).cdf).pvalue, 3))

Two output details deserve attention. First, the two Kolmogorov–Smirnov pp values are identical. This is no accident: the KS statistic is invariant under monotone transformations, and comparing F−1(U)F^{-1}(U) with FF is exactly the same as comparing UU with the uniform; the test evaluates the uniforms, not the formula. To detect an error in an inversion formula it must be compared with another reference, as with gamma. Second, Brent gives nearly machine precision but costs hundreds of times more per sample than the table, and the table fails precisely where density is small, in the tails. PINV combines the best: one-time setup and certified uu error on the order of 10−1010^{-10}.

Rejection sampling

When even FF is intractable, but you can evaluate density ff (even unnormalized), rejection works with only an easy-to-sample proposal gg and a constant raising it above ff.

The picture that explains everything: point (Y,U Mg(Y))(Y, U\,M g(Y)) is uniform under the graph of MgM g, a region of area MM. Conditioning on falling under the graph of ff (area 1) gives a uniform point under ff, and the horizontal coordinate of a uniform point under a density has that density. The probability of falling under ff is the area ratio, 1/M1/M. You will give the full analytic proof in the guided exercise.

Three practical consequences:

  • Normalization is unnecessary. If you know only f~=Zf\tilde f = Z f and g~\tilde g, with f~≤Mg~\tilde f \le M \tilde g, the algorithm works the same with f~/(Mg~)\tilde f/(M\tilde g); acceptance becomes Zf/(MZg)Z_f/(M Z_g). This is common in Bayesian statistics, where the posterior normalizing constant is unknown.
  • The proposal must have tails at least as heavy as the target. If f/g→∞f/g \to \infty in a tail, no MM exists. You can sample a normal with a Cauchy proposal, but not a Cauchy with a normal proposal.
  • If MM is too small, the result is silently wrong. Where f>Mgf > M g all proposals are accepted, but too few are proposed, and samples follow normalized density min⁡(f,Mg)\min(f, Mg). No exception warns you.
InteractiveRejection darts
  • target ff
  • envelope MgM g
  • accepted dart
  • rejected dart
  • histogram of accepted darts
Proposals per accepted sample, 2d/Vd2^d/V_d, on a log⁡10\log_{10} scale versus dimension dd
  • exact 2d/Vd2^d/V_d
  • estimated with 20,000 points
  • 20,000 point limit: above it, almost none are accepted
1.00
Lower panel: ball from cube
5
M∗=sup⁡xf(x)/g(x)M^* = \sup_x f(x)/g(x)2.458
MM2.458
Theoretical acceptance 1/M1/M40.7 %
Observed acceptance (633 of 1500)42.2 %
Ball in [−1,1]5[-1, 1]^{5}: exact acceptance0.1645
Proposals per sample, 2d/Vd2^d/V_d6.08
Observed with 20,000 points3218 inside
Above, target density ff (orange), envelope MgMg (dashed), and darts (Y,U Mg(Y))(Y, U\,M g(Y)): green if they fall under ff and are accepted, red otherwise. The accepted histogram converges to ff and observed rate to 1/M1/M. Try the Beta(1.5, 3) proposal, closer to Beta(2, 5): M∗M^* falls and far fewer are rejected. Lower M/M∗M/M^* below 1 and notice the red region where the envelope does not cover: the histogram stays below ff. Below, the mean number of proposals per accepted sample, 2d/Vd2^d/V_d, when sampling the unit ball of Rd\R^d by proposing uniform points from cube [−1,1]d[-1, 1]^d, on a logarithmic scale; above the red line, 20,000 proposals are no longer enough on average to accept even one.

Collapse in high dimensions

Rate 1/M1/M is an innocent number in one dimension. In dd dimensions, for targets and proposals factoring by coordinates, constants multiply: Md=M1dM_d = M_1^d. Acceptance falls exponentially with dimension.

The cleanest example is in the figure: sampling the unit ball of Rd\R^d by proposing points from cube [−1,1]d[-1, 1]^d. Acceptance is the volume ratio,

Vd2d,Vd=πd/2Γ(d/2+1),\frac{V_d}{2^d}, \qquad V_d = \frac{\pi^{d/2}}{\Gamma(d/2 + 1)},

which is π/4≈0.785\pi/4 \approx 0.785 in the plane, 0.1640.164 in d=5d = 5 and 2.5×10−82.5\times 10^{-8} in d=20d = 20, about 40 million proposals per sample. Almost all the cube’s volume lies in its corners, far from the ball. The same happens with a normal proposal slightly wider than the target: with f=N(0,Id)f = \Normal(\vb{0}, \mat{I}_d) and g=N(0,σ2Id)g = \Normal(\vb{0}, \sigma^2\mat{I}_d), σ>1\sigma > 1, ratio f/g=σde−∥x∥2(1−σ−2)/2f/g = \sigma^d e^{-\norm{\vb{x}}^2(1 - \sigma^{-2})/2} reaches its maximum at the origin, M=σdM = \sigma^d, and with σ=1.1\sigma = 1.1 and d=100d = 100 acceptance is 1.1−100≈7×10−51.1^{-100} \approx 7\times 10^{-5}. Thus pure rejection is a low-dimensional tool, and in high dimensions one turns to MCMC, which no longer produces independent samples but does not pay that exponential price. The same curse reappears in Monte Carlo integration in high dimensions.

Lab: rejection

[ ]Rejection: a beta, a truncated normal and dimensionBrowser
import numpy as np
from scipy import stats, special

g = np.random.default_rng(7)

def rechazo(f, propuesta, densidad_g, M, n):
    """Vectorizado por tandas; devuelve n muestras y el número de propuestas usadas."""
    out, usadas = [], 0
    while sum(len(o) for o in out) < n:
        m = int(1.2 * M * (n - sum(len(o) for o in out))) + 16
        y = propuesta(m)
        acepta = g.random(m) * M * densidad_g(y) <= f(y)
        out.append(y[acepta]); usadas += m
    x = np.concatenate(out)
    return x[:n], usadas * n / len(x)

# Beta(2, 5) desde la uniforme: M* = f(moda) = f(1/5)
f_beta = lambda x: 30 * x * (1 - x) ** 4
M = f_beta(0.2)
x, usadas = rechazo(f_beta, g.random, np.ones_like, M, 100_000)
print(f"Beta(2,5): M = {M:.4f}, 1/M = {1 / M:.4f}, aceptación observada = {len(x) / usadas:.4f},"
      f"  KS p = {stats.kstest(x, 'beta', args=(2, 5)).pvalue:.3f}")

# normal truncada a [a, ∞): ingenua frente a propuesta exponencial desplazada (Robert, 1995)
a = 4.0
print(f"ingenua (normal y quedarse con X > {a}): aceptación = 1 − Φ(a) = {stats.norm.sf(a):.2e}")
lam = (a + np.sqrt(a * a + 4)) / 2                       # tasa óptima de la exponencial
f_tn = lambda x: np.exp(-x * x / 2)                      # sin normalizar
g_tn = lambda x: lam * np.exp(-lam * (x - a))
M_tn = np.exp(lam * lam / 2 - lam * a) / lam             # sup de f/g, alcanzado en x = λ
x, usadas = rechazo(f_tn, lambda m: a + g.exponential(1 / lam, m), g_tn, M_tn, 100_000)
Z = np.sqrt(2 * np.pi) * stats.norm.sf(a)                # masa de f sin normalizar
print(f"exponencial: aceptación teórica Z/M = {Z / M_tn:.4f}, observada = {len(x) / usadas:.4f},"
      f"  KS p = {stats.kstest(x, stats.truncnorm(a, np.inf).cdf).pvalue:.3f}")

# dimensión: bola desde el cubo y normal desde una normal más ancha
for d in (2, 5, 8):
    pts = g.uniform(-1, 1, size=(200_000, d))
    obs = np.mean((pts ** 2).sum(1) <= 1)
    exacta = np.pi ** (d / 2) / special.gamma(d / 2 + 1) / 2**d
    print(f"bola d = {d:2d}: exacta {exacta:.5f}, observada {obs:.5f}")
for d in (1, 10, 100):
    print(f"N(0, I) desde N(0, 1.1² I), d = {d:3d}: aceptación 1.1^-d = {1.1 ** -d:.2e}")

The figures confirm the theory. Beta(2, 5) from the uniform accepts 40.7% (1/M1/M with M=2.4576M = 2.4576). For the normal truncated at a=4a = 4, the naive method accepts 3 of every 100000 normals, while the shifted exponential with Robert’s optimal rate accepts 97.5%: proposal choice changes cost by four orders of magnitude. And ball acceptance falls from 0.7850.785 in the plane to less than 0.020.02 in eight dimensions.

Fast normals: polar and Ziggurat

The normal is the most sampled distribution and deserves dedicated algorithms. The starting point is Box–Muller: with U1,U2U_1, U_2 independent uniforms,

X=−2log⁡U1cos⁡(2πU2),Y=−2log⁡U1sin⁡(2πU2)X = \sqrt{-2\log U_1}\cos(2\pi U_2), \qquad Y = \sqrt{-2\log U_1}\sin(2\pi U_2)

are two independent standard normals. It costs one logarithm, square root, sine and cosine per pair.

The polar method of Marsaglia and Bray (1964) removes sine and cosine. Generate (V1,V2)(V_1, V_2) uniformly in square [−1,1]2[-1, 1]^2 and reject it if S=V12+V22≥1S = V_1^2 + V_2^2 \ge 1 or S=0S = 0; if accepted, return

X=V1−2log⁡SS,Y=V2−2log⁡SS.X = V_1\sqrt{\frac{-2\log S}{S}}, \qquad Y = V_2\sqrt{\frac{-2\log S}{S}}.

It is correct for a geometric reason. The accepted point is uniform in the unit disk, so in polar coordinates V=S(cos⁡Θ,sin⁡Θ)V = \sqrt{S}(\cos\Theta, \sin\Theta), with P(S≤s)=πs/π=s\Pr(S \le s) = \pi s/\pi = s: SS is uniform on (0,1)(0, 1), Θ\Theta is uniform on [0,2π)[0, 2\pi), and both are independent. Also V1/S=cos⁡ΘV_1/\sqrt S = \cos\Theta and V2/S=sin⁡ΘV_2/\sqrt S = \sin\Theta. Substituting, X=−2log⁡Scos⁡ΘX = \sqrt{-2\log S}\cos\Theta and Y=−2log⁡Ssin⁡ΘY = \sqrt{-2\log S}\sin\Theta: this is Box–Muller with U1=SU_1 = S and 2πU2=Θ2\pi U_2 = \Theta, and rejection has manufactured sine and cosine for free. It accepts with probability π/4≈0.785\pi/4 \approx 0.785, so consumes an average of 8/π≈2.558/\pi \approx 2.55 uniforms per pair.

The Ziggurat of Marsaglia and Tsang (2000) goes further: in the vast majority of cases it evaluates no function. It covers half-density f(x)=e−x2/2f(x) = e^{-x^2/2}, x≥0x \ge 0 (unnormalized: rejection does not need it), with nn horizontal layers of equal area vv. The bottom layer consists of rectangle [0,r]×[0,f(r)][0, r] \times [0, f(r)] and the entire region under ff beyond point rr, the tail; its area, rf(r)+∫r∞fr f(r) + \int_r^\infty f, is set equal to vv. To sample it, use a rectangle of the same area, [0,v/f(r)]×[0,f(r)][0, v/f(r)] \times [0, f(r)]: a point with x<rx < r falls in the rectangular part, and one with x≥rx \ge r, occurring with probability equal to the tail’s relative mass, is replaced by a tail sample. Above it, layer ii is rectangle [0,xi]×[f(xi),f(xi+1)][0, x_i] \times [f(x_i), f(x_{i+1})], with x1=rx_1 = r and xix_i decreasing to the top; equality of areas gives the recurrence

xi (f(xi+1)−f(xi))=v⟹xi+1=f−1 ⁣(vxi+f(xi)),x_i\,\big(f(x_{i+1}) - f(x_i)\big) = v \quad\Longrightarrow\quad x_{i+1} = f^{-1}\!\Big(\frac{v}{x_i} + f(x_i)\Big),

and rr is adjusted (by bisection) so the last layer closes exactly at the top, xn−1(1−f(xn−1))=vx_{n-1}(1 - f(x_{n-1})) = v. Since layers have equal area, choosing a random layer and a uniform point within it chooses a uniform point in their union, containing the region under ff: rejection sampling with a proposal made of rectangles. The algorithm:

  1. Choose a layer ii uniform in {0,…,n−1}\{0, \dots, n - 1\} and x=U xix = U\,x_i, with x0=v/f(r)x_0 = v/f(r) the base width.
  2. Fast path: if x<xi+1x < x_{i+1}, the point lies under the curve regardless of height, because f(x)>f(xi+1)f(x) > f(x_{i+1}) and f(xi+1)f(x_{i+1}) is the layer’s maximum height (at the base, the condition is x<x1=rx < x_1 = r): accept xx.
  3. Otherwise, if it is the base, the sample is in the tail: generate it with Marsaglia’s tail method (1964), which repeats ξ=−log⁡(U1)/r\xi = -\log(U_1)/r, η=−log⁡(U2)\eta = -\log(U_2) until 2η>ξ22\eta > \xi^2 and returns r+ξr + \xi.
  4. Otherwise you are in the wedge between xi+1x_{i+1} and xix_i: generate uniform height yy in [f(xi),f(xi+1)][f(x_i), f(x_{i+1})] and accept if y<f(x)y < f(x). Otherwise return to step 1.

The full normal is obtained with a sign bit. In the real implementation, step 1 and the comparison in step 2 use a single random integer and a precomputed table of xi+1/xix_{i+1}/x_i: one random number, one lookup and one comparison.

InteractiveZiggurat layers
  • fast path (x<xi+1x < x_{i+1})
  • accepted wedge
  • rejected wedge
  • tail (x>rx > r)
  • e−x2/2e^{-x^2/2}
Theoretical fast-path fraction versus log⁡2n\log_2 n
8
Start of tail, rr2.3384
Area of each layer, vv0.1762
Fast path, theoretical 1n∑ixi+1/xi\frac1n\sum_i x_{i+1}/x_i72.80 %
Fast path, observed (300 attempts)74.00 %
Accepted wedge11.0 %
Rejected wedge13.3 %
Tail1.67 %
The half-density e−x2/2e^{-x^2/2} covered by nn equal-area layers. Each point is an attempt: blue if it falls inside its layer (x<xi+1x < x_{i+1}) and is accepted without evaluation; aquamarine or red if in the wedge and compared with e−x2/2e^{-x^2/2}; magenta if in the base beyond rr and sent to the tail. Blue point height is only for drawing: the algorithm does not generate it. Raise nn from 4 to 256 and watch wedges narrow and the blue fraction grow; the lower graph shows it for each nn. With n=128n = 128, rr and vv are those of Marsaglia and Tsang's paper.

The fraction of attempts resolved by the fast path is 1n∑i=0n−1xi+1/xi\frac1n\sum_{i=0}^{n-1} x_{i+1}/x_i, because layer ii is chosen with probability 1/n1/n and, within it, xx is uniform in [0,xi][0, x_i]. The next cell computes it for each nn: with 128 layers it is 97.2% and with 256, 98.5%. NumPy uses a 256-layer Ziggurat in Generator for normal, exponential and gamma, and its documentation presents it as 2 to 10 times faster than legacy-interface methods.

On the GPU the calculation changes. Ziggurat and rejection are branching algorithms: if one thread of a warp falls in the wedge and the other 31 do not, all wait for it to finish. GPU libraries therefore prefer branchless methods: cuRAND documentation says its normal-pair functions (curand_normal2) use Box–Muller.

Once you have independent standard normals, any multivariate normal N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) comes from multiplication by the Cholesky factor of Σ\mat{\Sigma} (Gaussian sampling with Cholesky); the cost of generating normals becomes secondary to that multiplication.

Lab: normals

[ ]Box–Muller, polar and a simplified ZigguratBrowser
import numpy as np, time, math
from scipy import stats, special

g = np.random.default_rng(11)
n = 200_000

def box_muller(n):
    u1, u2 = 1.0 - g.random(n // 2), g.random(n // 2)    # u1 en (0, 1]: nunca log(0)
    r = np.sqrt(-2 * np.log(u1))
    return np.concatenate([r * np.cos(2 * np.pi * u2), r * np.sin(2 * np.pi * u2)])

def polar(n):
    out, total = [], 0
    while total < n:
        v = g.uniform(-1, 1, size=(int(0.66 * (n - total)) + 16, 2))
        s = (v ** 2).sum(1)
        ok = (s < 1) & (s > 0)
        v, s = v[ok], s[ok]
        k = v * np.sqrt(-2 * np.log(s) / s)[:, None]
        out.append(k.ravel()); total += k.size
    return np.concatenate(out)[:n]

# tablas del Ziggurat (n = 128) por bisección sobre r
f = lambda x: np.exp(-0.5 * x * x)
finv = lambda y: np.sqrt(-2 * np.log(y))
cola = lambda r: np.sqrt(np.pi / 2) * special.erfc(r / np.sqrt(2))
def tablas(N):
    def construir(r):
        v = r * f(r) + cola(r); xs = [r]
        for _ in range(N - 2):
            y = v / xs[-1] + f(xs[-1])
            if y >= 1: return None, v
            xs.append(finv(y))
        return xs, v
    lo, hi = 0.5, 10.0
    for _ in range(100):
        mid = (lo + hi) / 2
        xs, v = construir(mid)
        if xs is None or xs[-1] * (1 - f(xs[-1])) < v: lo = mid
        else: hi = mid
    xs, v = construir(hi)
    return hi, v, np.array([v / f(hi)] + xs + [0.0])
for N in (8, 32, 128, 256):
    r, v, X = tablas(N)
    print(f"n = {N:3d}: r = {r:.6f}, v = {v:.6e}, vía rápida = {np.mean(X[1:] / X[:-1]):.4f}")
r, v, X = tablas(128)

def via_lenta(i, xi):
    """Intento que no ha pasado la vía rápida: cola (capa 0) o cuña. None si se rechaza."""
    if i == 0:
        while True:                                    # cola de Marsaglia (1964)
            a, b = -math.log(1 - g.random()) / r, -math.log(1 - g.random())
            if 2 * b > a * a:
                return r + a
    y = f(X[i]) + g.random() * (f(X[i + 1]) - f(X[i]))
    return xi if y < f(xi) else None

def intento_completo():
    while True:
        i = int(g.integers(0, 128)); xi = g.random() * X[i]
        if xi < X[i + 1]:
            return xi
        v = via_lenta(i, xi)
        if v is not None:
            return v

def ziggurat(n):
    capa = g.integers(0, 128, n)
    x = g.random(n) * X[capa]
    rapida = x < X[capa + 1]                           # la comparación de la vía rápida, vectorizada
    out = x.copy()
    lentas = np.flatnonzero(~rapida)
    for k in lentas:                                   # cada intento lento se resuelve, uno a uno, en Python
        v = via_lenta(int(capa[k]), x[k])
        out[k] = v if v is not None else intento_completo()   # si se rechaza, se repite el algoritmo entero
    signo = np.where(g.random(n) < 0.5, -1.0, 1.0)
    return signo * out, rapida.mean(), len(lentas)

for nombre, fn in [("Box-Muller", box_muller), ("polar", polar), ("NumPy (Ziggurat 256)", g.standard_normal)]:
    t0 = time.perf_counter(); z = fn(n); dt = time.perf_counter() - t0
    print(f"{nombre:22s} KS p = {stats.kstest(z, 'norm').pvalue:.3f}   {dt / n * 1e9:6.1f} ns por muestra")
t0 = time.perf_counter(); z, frac, lentas = ziggurat(n); dt = time.perf_counter() - t0
print(f"{'Ziggurat simplificado':22s} KS p = {stats.kstest(z, 'norm').pvalue:.3f}   {dt / n * 1e9:6.1f} ns por muestra"
      f"   (vía rápida {frac:.3f}; {lentas} intentos lentos en Python)")

The rr and vv for n=128n = 128 match Marsaglia and Tsang’s paper (r=3.442620r = 3.442620, v=9.912563×10−3v = 9.912563\times 10^{-3}), and all four samplers pass the Kolmogorov–Smirnov test. Times, however, need care: in NumPy what matters is how many array passes each method makes, not how many functions it evaluates. Vectorized Box–Muller and polar cost practically the same; the simplified Ziggurat is several times slower than both, because it resolves slow attempts (2.8%, about 5500 of 200000) with a Python loop, by far the most expensive part per element; and standard_normal, a Ziggurat in C, beats them all. Ziggurat’s algorithmic advantage (almost never evaluating exp⁡\exp) materializes only in compiled scalar code, where each sample is a handful of instructions.

Discrete distributions

To sample a categorical distribution with probabilities p1,…,pnp_1, \dots, p_n, three useful algorithms have very different costs.

The Walker–Vose alias method

Walker (1974) observed that any distribution over nn values can be written as a uniform mixture of nn distributions of at most two values. Scale probabilities to qi=npiq_i = n p_i, whose mean is 1. Columns with qi<1q_i < 1 are small and the others large. Each step takes a small ss and a large ℓ\ell, fills column ss to height 1 with mass from ℓ\ell (recording prob[s]=qs\text{prob}[s] = q_s and alias[s]=ℓ\text{alias}[s] = \ell), and subtracts from ℓ\ell the amount donated, qℓ←qℓ+qs−1q_\ell \leftarrow q_\ell + q_s - 1. To sample, choose a uniform column jj and an UU; if U<prob[j]U < \text{prob}[j] return jj, otherwise alias[j]\text{alias}[j].

Proof

Invariant. At the start of each step, the sum of qq of unclosed columns equals their number. Initially ∑inpi=n\sum_i n p_i = n. A step closes column ss, contributing qsq_s, and removes 1−qs1 - q_s from ℓ\ell: the sum decreases by qs+(1−qs)=1q_s + (1 - q_s) = 1, as does the number of open columns. Also qℓq_\ell remains nonnegative, because qℓ+qs−1≥qs≥0q_\ell + q_s - 1 \ge q_s \ge 0 since qℓ≥1q_\ell \ge 1.

Termination. If any small column remains open, by the invariant there must be one with q>1q > 1, which is large; so the step is always possible while small ones remain. Each step closes one column, so there are at most nn steps, each in O(1)\bigO(1) with two lists. Columns left open at the end all have q=1q = 1 (by the invariant, if none are small and the mean is 1) and are closed with prob=1\text{prob} = 1.

Correctness. The mass of column ii is never created or destroyed: npin p_i is distributed between the lower part of its own column, prob[i]\text{prob}[i], and the upper parts of columns having it as alias, 1−prob[j]1 - \text{prob}[j] for each jj with alias[j]=i\text{alias}[j] = i. Since each column is chosen with probability 1/n1/n,

P(salida=i)=1n(prob[i]+∑j: alias[j]=i(1−prob[j]))=npin=pi.\Pr(\text{salida} = i) = \frac1n\Big(\text{prob}[i] + \sum_{j:\ \text{alias}[j] = i}(1 - \text{prob}[j])\Big) = \frac{n p_i}{n} = p_i.∎

The two-list version is Vose’s (1991), who also studied floating-point robustness: rounding can leave a “large” column with qℓ=0.9999999999q_\ell = 0.9999999999 at the end, and the correct way to finish is to close whatever remains in either list with prob=1\text{prob} = 1.

InteractiveThe alias table
→ 1→ 2→ 1→ 2→ 3123456
Probability pip_i (outline) and observed frequency (fill)
0.3000.2500.2000.1200.0800.050
  • height 1 line (the mean of the scaled columns)
  • active column in this step (border)
table complete
Table complete: nn columns of height 1, each with its own value below and at most one alias above.
Darts thrown1000
χ2\chi^2 with 5 degrees of freedom (mean 5)4.21
Scaled columns npin p_i with the height-1 line. Advance Vose's construction: at each step the outlined small column is filled to 1 with excess from the large one, which falls and moves to the appropriate list. At the end all columns have height 1 and at most two colors; the arrow indicates the alias. Throw darts: each chooses a random column and height, and its color is the returned value. The lower panel compares frequencies with pip_i.

The Gumbel-max trick

The standard Gumbel distribution has distribution function Φ(g)=exp⁡(−e−g)\Phi(g) = \exp(-e^{-g}) and is sampled by inversion: G=−log⁡(−log⁡U)G = -\log(-\log U).

Proof

Call pi=eaip_i = e^{a_i} and Z=∑ipiZ = \sum_i p_i. The density of GG is ϕ(g)=e−gexp⁡(−e−g)\phi(g) = e^{-g}\exp(-e^{-g}), and P(ai+Gi≤t)=Φ(t−ai)=exp⁡(−pie−t)\Pr(a_i + G_i \le t) = \Phi(t - a_i) = \exp(-p_i e^{-t}). Index kk wins if ak+Gk=ta_k + G_k = t and all others fall below tt (ties have probability zero):

P(arg max⁡=k)=∫−∞∞ϕ(t−ak)∏i≠kΦ(t−ai) ⁣dt=∫−∞∞pke−texp⁡(−pke−t)∏i≠kexp⁡(−pie−t) ⁣dt=∫−∞∞pke−te−Ze−t ⁣dt.\Pr(\argmax = k) = \int_{-\infty}^{\infty} \phi(t - a_k)\prod_{i \ne k}\Phi(t - a_i)\dd t = \int_{-\infty}^{\infty} p_k e^{-t} \exp(-p_k e^{-t})\prod_{i\ne k} \exp(-p_i e^{-t}) \dd t = \int_{-\infty}^{\infty} p_k e^{-t} e^{-Z e^{-t}} \dd t.

With substitution s=e−ts = e^{-t},  ⁣ds=−s ⁣dt\dd s = -s\dd t, the integral is ∫0∞pke−Zs ⁣ds=pk/Z\int_0^\infty p_k e^{-Zs}\dd s = p_k/Z.

∎

Its practical value lies in what it does not need: neither normalizing logits (use aia_i directly, without softmax), nor sequential cumulative sums. Everything is elementwise plus an argmax, perfectly parallel on a GPU. Taking the largest kk of ai+Gia_i + G_i gives a sample without replacement (the Gumbel-top-kk trick), and relaxing argmax with a temperature softmax gives the Gumbel-softmax estimator. It is also one way to implement token sampling. The numerical trap is the same as before: if U=1U = 1, −log⁡(−log⁡1)=+∞-\log(-\log 1) = +\infty and that token always wins, regardless of its logit. Generate UU in the open interval.

Lab: discrete distributions and speed

[ ]CDF, alias and Gumbel-maxBrowser
import numpy as np, time
from scipy import stats

g = np.random.default_rng(5)
V = 2000                                              # un «vocabulario» con ley de Zipf
p = 1 / np.arange(1, V + 1) ** 1.1
p /= p.sum()
n = 200_000

def por_cdf(p, n):
    return np.searchsorted(np.cumsum(p), g.random(n), side="right").clip(max=len(p) - 1)

def alias_walker(p):
    """Construcción directa O(n²): en cada paso, la columna abierta más baja y la más alta."""
    m = len(p)
    q = p * m
    prob, alias = np.ones(m), np.arange(m)
    abierta = np.ones(m, dtype=bool)
    for _ in range(m - 1):
        s = np.where(abierta, q, np.inf).argmin()
        l = np.where(abierta, q, -np.inf).argmax()
        if q[s] >= 1 - 1e-12: break
        prob[s], alias[s], abierta[s] = q[s], l, False
        q[l] -= 1 - q[s]
    return prob, alias

def por_alias(prob, alias, n):
    j = g.integers(0, len(prob), n)
    return np.where(g.random(n) < prob[j], j, alias[j])

def por_gumbel(logits, n, lote=500):
    out = []
    for _ in range(n // lote):
        u = g.random((lote, len(logits)))
        u = np.where(u == 0.0, np.finfo(float).tiny, u)   # U en (0, 1): ni −∞ ni +∞
        out.append(np.argmax(logits - np.log(-np.log(u)), axis=1))
    return np.concatenate(out)

t0 = time.perf_counter(); prob, alias = alias_walker(p); t_tabla = time.perf_counter() - t0
logits = np.log(p) + 3.7                              # una constante cualquiera: Gumbel-max no normaliza
for nombre, fn in [("CDF + búsqueda binaria", lambda: por_cdf(p, n)),
                   ("alias", lambda: por_alias(prob, alias, n)),
                   ("Gumbel-max", lambda: por_gumbel(logits, n // 40))]:
    t0 = time.perf_counter(); x = fn(); dt = time.perf_counter() - t0
    obs = np.bincount(x, minlength=V)[:50]             # las 50 categorías más probables, más el resto
    esp = p[:50] * len(x)
    obs = np.append(obs, len(x) - obs.sum()); esp = np.append(esp, len(x) - esp.sum())
    print(f"{nombre:24s} χ² p = {stats.chisquare(obs, esp).pvalue:.3f}   {dt / len(x) * 1e9:8.1f} ns por muestra")
print(f"construcción de la mesa de alias (versión O(n²) de esta celda): {t_tabla * 1e3:.0f} ms para n = {V}")

All three pass the chi-square test. Per-sample alias is several times faster than binary search, which takes about log⁡22000≈11\log_2 2000 \approx 11 steps per sample versus one lookup and one comparison. Gumbel-max is hundreds of times more expensive than both here, because it generates V=2000V = 2000 uniforms and two logarithms per sample. On a GPU, with the logit vector already in memory and one sample per sequence, the calculation reverses: Gumbel-max is an elementwise operation plus a reduction, without the CDF’s cumulative sum. Table construction in this cell is deliberately quadratic; in the code exercise you will write Vose’s linear one.

In libraries

ToolWhat’s insidePurpose
np.random.default_rng(semilla)Generator over PCG64default sampling in NumPy
np.random.Generator(np.random.Philox(clave))Philox4x64-10streams by key, random access with advance
Generator.random, .integers53 bits per float; Lemire’s integer methodunbiased uniforms and integers
Generator.standard_normal, .exponential256-layer Zigguratnormals and exponentials
Generator.choice(a, p=...)categorical with probabilitiesgeneral discrete sampling
scipy.stats.<dist>.rvs(random_state=rng)distribution-specific methodssampling any SciPy distribution
scipy.stats.samplingPINV, transformed rejection (UNU.RAN)automatic inversion and rejection for custom densities
scipy.stats.kstest, chisquaregoodness-of-fit testsvalidate a sampler
torch.Generator(device), torch.manual_seedMersenne Twister on CPU, Philox on CUDAPyTorch randomness with explicit state
secretsoperating system CSPRNGtokens, keys and passwords

torch.manual_seed(s) seeds the CPU generator and each GPU generator together. The CPU one is Mersenne Twister (its state, torch.Generator().get_state(), occupies 5056 bytes), and CUDA uses Philox with seed and offset. To prevent one part of code consuming another’s stream, pass an explicit torch.Generator to torch.randn(..., generator=gen), torch.multinomial or DataLoader. The latter seeds each worker’s global random state, PyTorch state and global NumPy state with different values, but does not touch np.random.Generator created in your Dataset constructor: those are copied unchanged to each worker, the failure from the motivation.

[ ]A Generator copied to every workerBrowser
import numpy as np, pickle

class Aumentaciones:
    def __init__(self):
        self.rng = np.random.default_rng(0)            # creado una vez, en el proceso principal
    def __call__(self):
        return self.rng.integers(0, 360, 4).tolist()   # cuatro ángulos de rotación

ds = Aumentaciones()
# el DataLoader envía una copia del dataset a cada trabajador (fork o pickle): la misma copia del estado
trabajadores = [pickle.loads(pickle.dumps(ds)) for _ in range(4)]
print("copias:", [w() for w in trabajadores])

# corrección: cada trabajador deriva su propio flujo de la semilla raíz y de su índice
raiz = np.random.SeedSequence(0)
for w, hijo in zip(trabajadores, raiz.spawn(4)):
    w.rng = np.random.default_rng(hijo)               # lo que haría un worker_init_fn
print("con SeedSequence.spawn:", [w() for w in trabajadores])

Common mistakes

Connections

  • The Monte Carlo estimators in the next lesson consume these samplers, and their error is analyzed assuming independent uniforms, exactly what a generator must imitate.
  • Randomized quasi-Monte Carlo replaces uniforms with low-discrepancy sequences, and variance-reduction techniques such as stratified sampling build on inversion.
  • Metropolis–Hastings and Gibbs use uniforms for acceptance and proposals generated by these algorithms; they address rejection’s collapse in high dimensions.
  • Token sampling with temperature, top-kk and top-pp samples a categorical distribution: CDF or Gumbel-max on modified logits.
  • Managing seeds for reproducible experiments, in generators and streams, relies on SeedSequence, skipping and this lesson’s counter-based generators.
  • The difference between a PRNG and a cryptographic generator is critical in privacy; randomized response and differential privacy mechanisms need noise nobody can predict.

Exercises

NumericAcceptance rate with the best M
You want to sample f=Beta(2,5)f = \mathrm{Beta}(2, 5), with density 30x(1−x)430x(1-x)^4 on [0,1][0, 1], by rejection with proposal g=Beta(2,4)g = \mathrm{Beta}(2, 4), of density 20x(1−x)320x(1-x)^3. With the smallest valid constant MM, what fraction of proposals is accepted on average?
NumericThe ball inside the cube in ten dimensions
You generate uniform points in the cube [−1,1]10[-1, 1]^{10} and keep those in the unit ball (the simplest rejection sampler for the ball). What fraction of points is accepted?
NumericModulo bias
A generator produces uniform bytes, x∈{0,…,255}x \in \{0, \dots, 255\}, and you choose a number from 0 to 99 with r=x mod 100r = x \bmod 100. What is the exact probability of obtaining r=42r = 42?
NumericHow much does Lemire reject?
With w=32w = 32-bit words, Lemire's method generates integers in {0,…,n−1}\{0, \dots, n - 1\} with n=6×108n = 6\times 10^8. With what probability does it reject a word?
NumericExact zeros in float32
You generate 10910^9 float32 uniforms with standard conversion u=⌊x/28⌋⋅2−24u = \lfloor x/2^8 \rfloor\cdot 2^{-24} from uniform 32-bit words xx. How many equal exactly 0 on average?
ProofWhy rejection works
Prove: Let ff and gg be densities on R\R with f≤Mgf \le M g. If independent pairs Yk∼gY_k \sim g, Uk∼Unif(0,1)U_k \sim \mathrm{Unif}(0, 1) are generated and the first with Uk≤f(Yk)/(Mg(Yk))U_k \le f(Y_k)/(M g(Y_k)) is accepted, the accepted value has density ff and the number NN of pairs used is geometric with mean MM.
0
Call AA the event “the pair (Y,U)(Y, U) is accepted” for a generic pair and let F(x)=∫−∞xfF(x) = \int_{-\infty}^x f.

Step 1 of 4. What is P(Y≤x, A)\Pr(Y \le x,\ A)?

QuizThirty-two processes
You launch 32 simulation processes, and process ii creates its Mersenne Twister with seed semilla_base + i. Which statements are correct?

More than one answer may be correct.

QuizWhy counters on the GPU?
What is the main reason cuRAND, PyTorch on CUDA and JAX use counter-based generators like Philox or Threefry?
QuizChoosing the proposal
You want to rejection-sample a standard Cauchy distribution, f(x)=1/(π(1+x2))f(x) = 1/(\pi(1 + x^2)). Which proposal permits this?
CodeVose's alias method
Implement construir_alias(p), taking an array of probabilities (nonnegative, sum 1) and returning (prob, alias) with Vose's O(n)\bigO(n) algorithm: scale to qi=npiq_i = n p_i, divide indices into two lists (small with q<1q < 1 and large), and while both types remain take one of each, close the small one and return the large one to the appropriate list. Anything remaining in either list is closed with prob = 1 (rounding). Also implement vectorized muestrear_alias(prob, alias, n, rng), returning n indices: uniform column j and j if rng.random() < prob[j], otherwise alias[j].
import numpy as np

def construir_alias(p):
  p = np.asarray(p, dtype=float)
  n = len(p)
  prob = np.ones(n)
  alias = np.arange(n)
  # tu código: q = n p, listas de pequeños y grandes, y el bucle de Vose
  return prob, alias

def muestrear_alias(prob, alias, n, rng):
  # tu código: columnas uniformes y una comparación por muestra
  return np.zeros(n, dtype=int)
Shift+Enter to run

Summary

Key idea
A pseudorandom generator is a deterministic function of state, and its quality is a structural property designed (period, equidistribution, nonlinear output) and tested (statistical batteries); samplers transform its uniforms into any distribution through three ideas: invert the distribution function, reject under an envelope, and precompute tables that do almost all the work with one comparison.
  • Congruential generators have lattice structure: RANDU triples lie on 15 planes because a2≡6a−9(mod231)a^2 \equiv 6a - 9 \pmod{2^{31}}. Generators linear over F2\mathbb{F}_2 (xorshift, Mersenne Twister) have bits with linear complexity bounded by their state, and therefore fail linear-complexity tests and are predictable. PCG and xoshiro break linearity with a nonlinear output.
  • Counter-based generators compute xi=gk(i)x_i = g_k(i): random access, streams by key and massive parallelism. They are the GPU generators (Philox in cuRAND and PyTorch, Threefry in JAX). Neither they nor statistical PRNGs are cryptographic: for secrets, secrets.
  • A uniform float is 53 bits scaled by 2−532^{-53}, with u=0u = 0 possible: use 1−u1 - u before a logarithm. A range integer with x % n is biased; Lemire’s method is exact and almost always costs one multiplication.
  • Inversion is exact if F−1F^{-1} is explicit, slow with Brent and fast with tables, whose error is measured in uu. Rejection accepts with probability 1/M1/M, needs f≤Mgf \le Mg (and fails silently otherwise), and collapses exponentially with dimension.
  • For normals, the polar method avoids sine and cosine with rejection of acceptance π/4\pi/4, and Ziggurat resolves 97% (128 layers) or 98.5% (256 layers) of attempts with one comparison. For discrete distributions: binary CDF search (O(log⁡n)\bigO(\log n)), Vose alias (O(1)\bigO(1) per sample after O(n)\bigO(n) setup), and Gumbel-max (unnormalized and parallel).