NumPy Random Generator Fundamentals
Random number generation is useful for simulations, sampling, testing,
statistical experiments, and machine learning workflows. NumPy provides
a modern random number generation system through
np.random.default_rng(). In this lesson, you will learn
how random generators work, how to generate random arrays, how seeds
support reproducibility, and how to use random data in practical programs.
1. Introduction to Random Number Generation
Random number generation produces values that behave like samples from a specified random process. Computers generally use algorithms to generate pseudorandom values, rather than generating every value from a physical random source.
NumPy's random module supports different kinds of random data, including floating-point numbers, integers, samples from arrays, and values from probability distributions.
Where Random Numbers Are Used
- Simulating real-world events and experiments.
- Generating sample datasets for testing programs.
- Selecting random samples from larger datasets.
- Initializing values in numerical and machine learning workflows.
- Studying probability distributions and statistical behavior.
- Running Monte Carlo simulations.
2. Creating a Random Generator
The recommended modern approach is to create a generator using
np.random.default_rng(). It returns a generator object
that provides methods for producing random values.
import numpy as np rng = np.random.default_rng() number = rng.random() print(number)
Example Output
0.483726...
The displayed decimal is only an illustration. Your value will normally be different because no fixed seed was provided.
The rng variable stores the generator object. You can reuse
this same generator to produce multiple random values and arrays.
3. Understanding Random Seeds
A seed initializes a pseudorandom number generator. Using the same seed with the same generator setup and the same sequence of operations produces reproducible results.
import numpy as np rng = np.random.default_rng(42) values = rng.random(5) print(values)
Example Output
[0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
This example uses seed 42. Repeating the program with the same NumPy environment, seed, and generator calls reproduces the same sequence.
Compare Two Generators
import numpy as np rng1 = np.random.default_rng(42) rng2 = np.random.default_rng(42) values1 = rng1.random(5) values2 = rng2.random(5) print(np.array_equal(values1, values2))
Output
True
Both generators begin from the same seed and perform the same operation, so their generated arrays match.
Using the same seed makes a pseudorandom sequence reproducible when generator usage matches.
4. Generating Random Floating-Point Numbers
The rng.random() method generates floating-point values
in the interval from 0 inclusive to 1 exclusive.
import numpy as np rng = np.random.default_rng(10) print(rng.random()) print(rng.random(5))
Example Output
0.9560017... [0.20768181 0.82844489 0.14928212 0.51280462 0.13591960]
Exact values depend on the seed and generator sequence. The first call returns one scalar value, while the second requests five values in a one-dimensional array.
Generate a Two-Dimensional Array
import numpy as np
rng = np.random.default_rng(10)
matrix = rng.random((2, 3))
print(matrix)
print("Shape:", matrix.shape)
Example Output
[[0.9560017 ... ...] [... ... ...]] Shape: (2, 3)
The ellipses above indicate omitted illustrative values. When you run
the complete code, NumPy prints the actual three values in each row.
The shape is always (2, 3).
5. Generating Random Integers
Use rng.integers() to generate random integer values.
Its upper bound is exclusive by default.
import numpy as np rng = np.random.default_rng(20) numbers = rng.integers(1, 7, size=10) print(numbers)
Example Output
[4 2 5 1 3 6 2 4 1 5]
This illustrative output contains ten values from 1 through 6. The actual values depend on the generator sequence.
Include the Upper Bound
import numpy as np rng = np.random.default_rng(20) numbers = rng.integers(1, 7, size=10, endpoint=True) print(numbers)
When endpoint=True, the upper bound is included. Here,
the possible integer values range from 1 through 7.
Generate a Matrix of Random Integers
import numpy as np
rng = np.random.default_rng(25)
matrix = rng.integers(10, 100, size=(3, 4))
print(matrix)
print("Shape:", matrix.shape)
The array contains three rows and four columns. Each value is an integer from 10 through 99 because the upper bound 100 is excluded.
6. Generating Arrays with a Specified Shape
Many random generator methods accept a size parameter.
It determines the shape of the generated array.
| Size Argument | Result |
|---|---|
size=None |
Typically returns a scalar value. |
size=5 |
A one-dimensional array of five values. |
size=(2, 3) |
A two-dimensional array with two rows and three columns. |
size=(2, 3, 4) |
A three-dimensional array with shape (2, 3, 4). |
import numpy as np
rng = np.random.default_rng(30)
one_d = rng.random(5)
two_d = rng.random((2, 3))
three_d = rng.random((2, 3, 4))
print("1D shape:", one_d.shape)
print("2D shape:", two_d.shape)
print("3D shape:", three_d.shape)
Output
1D shape: (5,) 2D shape: (2, 3) 3D shape: (2, 3, 4)
You can use this technique to create test data, simulated measurements, batches of observations, and multidimensional numerical datasets.
7. Random Values Within a Custom Range
The random() method generates values between zero and one.
To generate floating-point values within another interval, scale and
shift the results.
import numpy as np rng = np.random.default_rng(40) low = 10 high = 50 values = low + (high - low) * rng.random(5) print(values)
The generated values lie between 10 inclusive and 50 exclusive.
This method works for a general interval of the form
[low, high).
Using a Uniform Distribution Directly
import numpy as np rng = np.random.default_rng(40) values = rng.uniform(10, 50, size=5) print(values)
rng.uniform() is a convenient way to generate samples
from a uniform distribution over the specified interval.
rng.uniform(low, high, size=...)
when the goal is to sample floating-point values across a range.
8. Reproducibility and Generator State
A random generator maintains an internal state. Each random-generation call advances that state, so consecutive calls usually produce different portions of the sequence.
import numpy as np
rng = np.random.default_rng(42)
first = rng.integers(1, 100, size=5)
second = rng.integers(1, 100, size=5)
print("First:", first)
print("Second:", second)
The two arrays normally differ because the generator advances between calls. Running the same program again with the same seed and call order reproduces both arrays.
Restart the Sequence
import numpy as np rng1 = np.random.default_rng(42) first_run = rng1.integers(1, 100, size=5) rng2 = np.random.default_rng(42) second_run = rng2.integers(1, 100, size=5) print(np.array_equal(first_run, second_run))
Output
True
9. Using Independent Random Generators
You can create separate generator objects for different tasks. This helps isolate random sequences so that adding an extra random call to one task does not necessarily change the other task's sequence.
import numpy as np
marks_rng = np.random.default_rng(100)
attendance_rng = np.random.default_rng(200)
marks = marks_rng.integers(40, 101, size=5)
attendance = attendance_rng.integers(60, 101, size=5)
print("Marks:", marks)
print("Attendance:", attendance)
The two generators have separate states. Their seeds can be chosen independently, making the two parts of the program easier to test and reproduce.
Using SeedSequence for Related Generators
import numpy as np seed_sequence = np.random.SeedSequence(12345) child_sequences = seed_sequence.spawn(2) rng_a = np.random.default_rng(child_sequences[0]) rng_b = np.random.default_rng(child_sequences[1]) print(rng_a.random(3)) print(rng_b.random(3))
SeedSequence.spawn() provides separate child seed
sequences suitable for initializing independent generator streams.
This is useful in simulations that divide work across multiple tasks.
10. Random Sampling from an Existing Array
The rng.choice() method selects values from an existing
one-dimensional array or sequence. You can request a single sample
or multiple samples.
import numpy as np
rng = np.random.default_rng(50)
students = np.array([
"Samadhan",
"Pradnya",
"Samiksha"
])
selected = rng.choice(students)
print("Selected student:", selected)
The selected student depends on the random generator. Every name in the input array is a possible choice.
Select Multiple Values Without Replacement
import numpy as np
rng = np.random.default_rng(50)
students = np.array([
"Samadhan",
"Pradnya",
"Samiksha"
])
selected = rng.choice(students, size=2, replace=False)
print(selected)
With replace=False, a value cannot be selected more
than once within the same sampling call. The requested sample size
cannot exceed the number of available elements.
Select Values with Replacement
selected = rng.choice(
students,
size=5,
replace=True
)
print(selected)
With replace=True, the same student name may appear
multiple times in the result.
11. Common Random Generator Methods
| Method | Purpose | Example |
|---|---|---|
rng.random() |
Uniform floating-point values in [0, 1). | rng.random(5) |
rng.integers() |
Random integer values. | rng.integers(1, 7, size=10) |
rng.uniform() |
Uniform floating-point values within a range. | rng.uniform(10, 20, size=5) |
rng.normal() |
Samples from a normal distribution. | rng.normal(0, 1, size=100) |
rng.choice() |
Samples from existing values. | rng.choice([1, 2, 3]) |
rng.permutation() |
Returns a permuted sequence or array. | rng.permutation(10) |
rng.shuffle() |
Shuffles an array in place along its first axis. | rng.shuffle(arr) |
Each method has its own rules for bounds, shape, and probability distributions. Read the method's documentation when those details are important to your application.
12. Practical Project: Random Student Marks
CIIT TRANING INSTITUTE wants to create sample examination marks for Samadhan, Pradnya, and Samiksha. We can use a random generator to produce reproducible sample data for testing an analysis program.
import numpy as np
rng = np.random.default_rng(2026)
students = np.array([
"Samadhan",
"Pradnya",
"Samiksha"
])
marks = rng.integers(
35,
101,
size=(3, 3)
)
totals = marks.sum(axis=1)
averages = marks.mean(axis=1)
passed = np.all(marks >= 40, axis=1)
print("Students:", students)
print("Marks:")
print(marks)
for i, name in enumerate(students):
print()
print("Student:", name)
print("Total:", totals[i])
print("Average:", round(averages[i], 2))
print("Passed all subjects:", passed[i])
The marks are random integers from 35 through 100. The fixed seed makes the sample data reproducible when the same generator setup and calls are used.
The totals, averages, and passing checks use vectorized NumPy operations. The final loop formats the results for each student.
13. Common Mistakes
Mistake 1: Forgetting That the Upper Bound Is Exclusive
rng.integers(1, 7) generates integers from 1 through
6 by default. Use endpoint=True if the upper bound
should be included.
Mistake 2: Expecting Different Results from Identically Seeded Generators
Two generators initialized with the same seed and used in the same way produce matching sequences. Use different seed initialization when independent sequences are needed.
Mistake 3: Resetting the Seed for Every Random Value
Reinitializing a generator repeatedly can restart its sequence and produce repeated patterns. Create a generator once and reuse it for the sequence of operations.
Mistake 4: Assuming Random Means Uniform
Random values follow the distribution specified by the method.
For example, rng.normal() samples from a normal
distribution, while rng.random() produces uniform
values in the interval [0, 1).
Mistake 5: Using NumPy for Security Tokens
NumPy's pseudorandom generators are intended for scientific computing. Use a cryptographically secure source for security tokens and secrets.
14. Practice Exercises
Exercise 1: Create a Generator
Create a generator with np.random.default_rng()
and generate five floating-point values.
Exercise 2: Reproducibility
Create two generators with seed 100. Generate ten integers from each and verify whether the arrays are equal.
Exercise 3: Generate a Matrix
Generate a 4 by 5 array of random integers between 10 and 99. Print the matrix and its shape.
Exercise 4: Custom Range
Generate ten floating-point values between 20 and 80 using
rng.uniform().
Exercise 5: Random Student Selection
Create an array containing Samadhan, Pradnya, and Samiksha. Randomly select one student and then select two distinct students.
Exercise 6: Random Marks Analysis
Generate marks for three students across four subjects. Calculate each student's total and average using NumPy.
Exercise 7: Independent Generators
Create two generators with different seeds. Generate five random values from each and compare their results.
Exercise 8: Mini Simulation
Simulate 100 dice rolls using integers from 1 through 6. Count how often each possible result occurs.
Summary
NumPy's modern random-generation interface uses
np.random.default_rng() to create a generator. Its
methods can generate floating-point values, integers, random samples,
and values from different probability distributions.
A fixed seed makes pseudorandom results reproducible when the
generator setup and sequence of calls remain consistent. The
size parameter controls the shape of generated arrays,
while methods such as rng.choice() support sampling
from existing values.
Reuse generator objects, select methods that match the required distribution, and use vectorized NumPy operations to analyze generated data. NumPy random generators are suitable for simulation and testing, but not for cryptographic secrets.