Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy random.randint()

NumPy's random and probability functions are used to generate random numbers and perform probabilistic operations efficiently. The `np.random.randint()` function specifically is used to generate random integers within a specified range.

Usage

The `np.random.randint()` function is typically used when you need random integers for simulations, testing, or any scenario requiring randomized data within a set range.

np.random.randint(low, high=None, size=None, dtype=int)
  • low: The lower (inclusive) boundary of the random integers.
  • high: The upper (exclusive) boundary of the random integers. If `high` is None, the range is [0, low). This means that calling `np.random.randint(10)` will generate a random integer from 0 to 9.
  • size: Output shape. If the given shape is, e.g., `(m, n, k)`, then `m * n * k` samples are drawn.
  • dtype: Desired data type of the result. Can be any integer type like `np.int32` or `np.int64`, which can be important for memory considerations or compatibility with other code.

Note: If `low` is greater than or equal to `high`, a `ValueError` will be raised, as the range would be invalid.

Examples

1. Basic Usage

import numpy as np

random_number = np.random.randint(10)

This example generates a random integer between 0 (inclusive) and 10 (exclusive).

2. Specifying a Range

import numpy as np

random_number = np.random.randint(5, 15)

Here, `np.random.randint(5, 15)` generates a random integer between 5 (inclusive) and 15 (exclusive).

3. Generating a Multi-Dimensional Array

import numpy as np

random_array = np.random.randint(1, 100, size=(3, 3))

This example creates a 3x3 array of random integers ranging from 1 to 99.

4. Specifying `dtype`

import numpy as np

random_number = np.random.randint(0, 100, dtype=np.int32)

This example generates a random integer between 0 and 99 with a `dtype` of `np.int32`.

Tips and Best Practices

  • Specify both `low` and `high`. Providing both parameters helps avoid unintended ranges and makes your intent clear.
  • Use `size` to control output shape. Set the `size` parameter for generating arrays instead of single values.
  • Ensure reproducibility. Use `np.random.seed()` before generating random numbers to ensure reproducible results, especially for testing.
  • Choose appropriate `dtype`. Make sure to use an appropriate `dtype` if you require a specific integer type beyond the default `int`.
  • Consider performance for large arrays. When generating large arrays, be mindful of memory usage and consider the `dtype` to optimize performance.