This site is version 0.0.1. Most of the code on this site is drafted by an agent and needs review. I apologize for the AI-speak, we are working on rewriting it!
viv-lang.org

Notebooks · lib/nprandom/legacy

NumPy's legacy random functions, over its Mersenne Twister

The functions np.random.rand, random_sample, uniform, randint, choice, shuffle and permutation draw from one MT19937 state (lib/nprandom/mt19937). Each def here is the NumPy 1.24.4 code path it names (numpy/random/mtrand.pyx, _bounded_integers.pyx.in, src/distributions/distributions.c; tag v1.24.4, commit 9315a9072b2636f75c831b4eca9f42a5f67ca2fb), with the draws in the same order, so a seeded Python program and its translation see the same numbers.

  • npr_lg_uniform(st, low, rng): random_uniform, low + rng * double.
  • npr_lg_bounded(st, rng): an int in [0, rng] by masked rejection (random_bounded_uint64 with use_masked): no draw when rng is 0, one 32-bit word per try while rng < 2^32 - 1, the word itself at 2^32 - 1, a 64-bit draw above. RandomState.randint(low, high) is low + npr_lg_bounded(high - 1 - low).
  • npr_lg_interval(st, mx): random_interval, the masked draw shuffle uses (the same draws as npr_lg_bounded for mx < 2^32 - 1).
  • npr_lg_shuffle(st, a), npr_lg_shuffle_rows(st, A): Fisher-Yates from the top index down, j = random_interval(i), then swap entries (or rows) i and j.
  • npr_lg_cdf(p), npr_lg_search(cdf, u): for choice with p=, the running sum of p divided by its last entry, and the count of entries at or below a draw (searchsorted(u, side='right')).
  • npr_kahan_sum(p): the sum NumPy checks p with.

The normal draws (randn, standard_normal, normal) are not here: NumPy computes them with the platform's log, whose last bit Viv's libm does not reproduce on every input, so no Viv code can promise NumPy's values.

Used with import nprandom.legacy.

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.

[1]lines 33–153