Random numbers in Python
The modern Generator API for reproducible randomness.
import numpy as np
rng = np.random.default_rng(seed=42)
uniform = rng.random(5)
rolls = rng.integers(1, 7, size=10)
sample = rng.normal(loc=0, scale=1, size=(2, 3))
deck = np.arange(52)
rng.shuffle(deck)
hand = rng.choice(deck, size=5, replace=False)
mean_roll = rolls.mean()
How it works
default_rng(seed)makes results reproducible.integersandnormaldraw from distributions.shuffleandchoicesample without replacement.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 13
- Characters to type
- 279
- Tokens
- 97
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 55 seconds.
Step 2 of 2 in Selection & random, step 8 of 22 in NumPy.