Skip to content
NumPy

Random Numbers

Sample from distributions with a Generator.

By EZ4Code Team
randomrng

Code

import numpy as np

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

uniform = rng.random((3, 3))
ints = rng.integers(0, 10, size=5)
normal = rng.standard_normal(5)
choice = rng.choice([10, 20, 30], size=4, p=[0.5, 0.3, 0.2])
shuffled = rng.permutation(np.arange(10))

# Sampling from distributions
gauss = rng.normal(loc=0, scale=1, size=4)
beta = rng.beta(2, 5, size=4)
binom = rng.binomial(10, 0.5, size=4)

print(uniform.shape, ints, normal, choice)

Explanation

default_rng creates a modern Generator with better statistical properties than the legacy global functions. A seed makes draws reproducible, which is essential for testing and debugging. The Generator offers uniform, normal, integer, and choice methods plus many named distributions.

More NumPy Snippets