8.3. NumPy Randomness#
Topic |
Legacy (global RNG) |
Modern (Generator API) |
|---|---|---|
Main objects |
|
|
Seeding |
|
|
State scope |
Global, shared across code |
Isolated per |
Typical calls |
|
|
Reproducibility |
Fragile (any call anywhere advances global state) |
Robust (each |
Performance/algorithms |
Older (MT19937); OK speed |
Newer bit-generators (PCG64 default), often faster/better |
Broadcasting/shape |
Functions accept |
Consistent |
Thread/process safety |
Global contention possible |
Use separate |
Legacy |
Modern (preferred) |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Call / Purpose |
Legacy (global RNG) |
Modern (Generator API) |
Example (legacy → modern) |
|---|---|---|---|
Seed |
|
|
|
Uniform floats |
|
|
|
Standard normal |
|
|
|
Integers |
|
|
|
Random sample / sample alias |
|
|
|
Uniform in [low, high) |
|
|
|
Binomial |
|
|
|
Poisson |
|
|
|
Permutation (returns permuted copy) |
|
|
|
Shuffle (in place) |
|
|
|
8.3.1. Array Attributes and Methods#
Randomness: rand, randn, randint
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
arr
ranarr
8.3.2. Random#
Numpy also has lots of ways to create random number arrays:
8.3.2.1. rand#
Create an array of the given shape and populate it with
random samples from a uniform distribution
over [0, 1).
np.random.rand(5)
np.random.rand(5,5)
8.3.2.2. randn#
Return a sample (or samples) from the “standard normal” distribution. Unlike rand which is uniform:
np.random.randn(5)
np.random.randn(5,5)
8.3.2.3. randint#
Return random integers from low (inclusive) to high (exclusive).
np.random.randint(1,100)
np.random.randint(1,100,10)