0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.random.randint in NumPy for Random Integers

Use np.random.randint(low, high=None, size=None, dtype=int) to generate random integers. It returns integers from low (inclusive) up to high (exclusive). If high is not given, it generates integers from 0 to low (exclusive).
๐Ÿ“

Syntax

The function np.random.randint has this syntax:

  • low: The lowest integer to be drawn (inclusive).
  • high: The upper bound (exclusive). If not provided, low is treated as high and low defaults to 0.
  • size: The shape of the output array. If None, returns a single integer.
  • dtype: The desired integer type (default is int).
python
np.random.randint(low, high=None, size=None, dtype=int)
๐Ÿ’ป

Example

This example shows how to generate a single random integer between 0 and 9, and an array of 5 random integers between 10 and 19.

python
import numpy as np

# Single random integer from 0 to 9
single_int = np.random.randint(10)

# Array of 5 random integers from 10 to 19
array_ints = np.random.randint(10, 20, size=5)

print('Single integer:', single_int)
print('Array of integers:', array_ints)
Output
Single integer: 7 Array of integers: [14 19 11 13 10]
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Confusing low and high values, which can cause errors or unexpected results.
  • Forgetting that high is exclusive, so the maximum integer generated is high - 1.
  • Not specifying size when an array is needed, resulting in a single integer instead of an array.
python
import numpy as np

# Wrong: low >= high causes ValueError
try:
    np.random.randint(10, 5)
except ValueError as e:
    print('Error:', e)

# Right: low < high
correct = np.random.randint(5, 10)
print('Correct random integer:', correct)
Output
Error: low >= high Correct random integer: 7
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
lowLowest integer (inclusive)Required
highHighest integer (exclusive)None (treated as low, with low=0)
sizeOutput shape (int or tuple)None (single integer)
dtypeOutput data typeint
โœ…

Key Takeaways

np.random.randint generates random integers from low (inclusive) to high (exclusive).
If high is not given, integers are from 0 to low (exclusive).
Use the size parameter to get arrays instead of single integers.
Ensure low is less than high to avoid errors.
Remember high is exclusive, so max integer is high minus one.