Notebooks · lib/random
Random draws, each one a formula over rand()
Viv's rand() is Park-Miller MINSTD: srand(seed) sets the state to
floor(|seed|) mod 2147483646 + 1, and each rand() moves it to
16807 * state mod 2147483647 and returns state / 2147483647, a number in
(0, 1). Every product stays below 2^53, so the state is exact in a double, the
interpreter and compiled C and wasm draw the same stream, and a Python program
can replay it (tools/random_replay.py).
The draws here are plain Viv over that one generator, so they are identical in every engine by construction. Each is documented as the exact formula it computes, draw by draw, so a reference implementation can replay it:
randn(): Box-Muller, cosine branch.u1 = rand()first, thenu2 = rand(), and the result issqrt(-2 log(u1)) * cos(2 pi u2). One normal per two uniforms; the sine branch is not kept.randn_matrix(rows, cols):randn()for each entry, row by row.randint(lo, hi): an integer in[lo, hi),lo + floor(rand() * (hi - lo)), as Python'srandom.randrange(lo, hi)andtorch.randint(lo, hi)bound it.shuffle(a): Fisher-Yates in place, from the top index down. Fori = n - 1, ..., 1,j = floor(rand() * (i + 1))anda[i]swaps witha[j].randperm(n):shuffle(arange(n)).choice(p): an index drawn with the probabilitiesp(a 1-D array that sums to 1) by inverting the cumulative sum at one draw:u = rand(), and the answer is the firstkwithu < p[0] + ... + p[k], or the last index if rounding leaves the sum short ofu.arange(n):[0, 1, ..., n - 1].pi: 3.141592653589793, the double nearest pi.
mean and std are in lib/stats, so a program that draws numbers but keeps
a variable called std can still use this module.
Used with import random.
Look inside this program
- Atlas
The program’s map: every function and which calls which.
There’s no recorded run of this program yet.
Shift+Enter in a cell runs it and moves to the next. Running a cell runs every cell above it too, as one program.