NumPy Randint: Generate Random Integers
The np.random.randint function is used to generate random integers within a specified range.
The syntax of the function is:
np.random.randint(low, high=None, size=None, dtype=int)
Explanation of parameters:
- Minimum value (inclusive) of the generated random numbers.
- high: The upper limit (excluding) of the generated random number. If this parameter is not specified, the maximum value of the random number will be the same as the low value.
- Size: The number or shape for generating random numbers. If specified as an integer, it will generate a one-dimensional array with that number of elements; if specified as a tuple or list, it will generate an array with that shape. Default is None, indicating the generation of a single random number.
- dtype: The data type used to generate random numbers, which defaults to integer type.
Here are some examples of using the np.random.randint function:
- Generate a random integer:
import numpy as np
Generate a random number between 0 and 9 using NumPy and print it.
Output: a random integer between 0 and 9.
- Create a random integer within a specified range:
rand_num = np.random.randint(1, 10)
print(rand_num)
Output: a random integer between 1 and 9
- Create an array of multiple random integers within a specified range:
rand_arr = np.random.randint(1, 10, size=5)
print(rand_arr)
Output: a one-dimensional array containing 5 random integers between 1 and 9.
- Create a random integer array with a specified shape:
rand_arr = np.random.randint(1, 10, size=(2, 3))
print(rand_arr)
Output: A 2 by 3 random integer array with elements ranging from 1 to 9.
These are just some common uses of the np.random.randint function, and the parameters can be adjusted flexibly according to specific needs.