typestar

The Generator API in Python

np.random.default_rng is the modern, seedable source of randomness.

import numpy as np

rng = np.random.default_rng(seed=7)

print(rng.integers(0, 10, size=5))
print(rng.normal(loc=100, scale=15, size=3).round(2))
print(rng.choice(["python", "rust", "sql"], size=4))
print(rng.permutation(np.arange(5)))

again = np.random.default_rng(seed=7)
print(np.array_equal(again.integers(0, 10, size=5), np.array([0, 8, 0, 2, 3])))

How it works

  1. A Generator carries its own state, unlike the legacy functions.
  2. Passing a seed makes a run reproducible.
  3. choice samples with or without replacement.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
354
Tokens
143
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 1 of 2 in Randomness & storage, step 20 of 22 in NumPy.

← Previous Next →