0
0
NumPydata~5 mins

Integer random with integers() in NumPy

Choose your learning style9 modes available
Introduction

We use integers() to get random whole numbers easily for simulations or testing.

When you want to simulate rolling dice in a game.
When you need random IDs for test data.
When you want to pick random indexes from a list.
When you want to generate random counts or quantities.
When you want to create random samples of integers for experiments.
Syntax
NumPy
numpy.random.Generator.integers(low, high=None, size=None, dtype=int, endpoint=False)

low is the smallest integer you want.

high is one more than the largest integer you want (unless endpoint=True).

Examples
Random integer from 1 to 6 (like a dice roll).
NumPy
rng.integers(1, 7)
Array of 5 random integers from 0 to 9.
NumPy
rng.integers(0, 10, size=5)
Random integer from 1 to 5 including 5.
NumPy
rng.integers(1, 5, endpoint=True)
Sample Program

This code shows how to get random integers using integers(). It creates a random number generator, then gets one dice roll, an array of 5 random numbers, and one number including the endpoint.

NumPy
import numpy as np

rng = np.random.default_rng()

# Get one random integer from 1 to 6
single_roll = rng.integers(1, 7)

# Get 5 random integers from 0 to 9
random_array = rng.integers(0, 10, size=5)

# Get one random integer from 1 to 5 including 5
inclusive_roll = rng.integers(1, 5, endpoint=True)

print(f"Single dice roll (1-6): {single_roll}")
print(f"Array of 5 random integers (0-9): {random_array}")
print(f"Inclusive roll (1-5): {inclusive_roll}")
OutputSuccess
Important Notes

Use size to get multiple random numbers at once.

By default, high is exclusive, so numbers go up to high - 1.

Set endpoint=True to include the high value.

Summary

integers() gives random whole numbers in a range.

You can get single numbers or arrays of numbers.

Remember the high value is usually not included unless you say so.