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,lowis treated ashighandlowdefaults to 0.size: The shape of the output array. If None, returns a single integer.dtype: The desired integer type (default isint).
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
lowandhighvalues, which can cause errors or unexpected results. - Forgetting that
highis exclusive, so the maximum integer generated ishigh - 1. - Not specifying
sizewhen 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
| Parameter | Description | Default |
|---|---|---|
| low | Lowest integer (inclusive) | Required |
| high | Highest integer (exclusive) | None (treated as low, with low=0) |
| size | Output shape (int or tuple) | None (single integer) |
| dtype | Output data type | int |
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.