NumPy’s random module lets you generate high-quality random numbers for simulations, sampling, and data science tasks. You need Python installed and the NumPy library—no additional hardware or software required.
What You'll Need
- Python 3.7 or newer (recommended)
- NumPy library (install via
pip install numpy) - A Python environment (e.g., terminal, Jupyter Notebook, or IDE like VS Code)
Step-by-Step
- Open your Python environment (e.g., start Python in a terminal, launch Jupyter Notebook, or open a `.py` file in your IDE).
- Import NumPy at the top of your script or notebook cell using
import numpy as np. This creates the standard aliasnpfor concise code. - Choose the type of random number you need. NumPy supports integers, floats, arrays of various shapes, and distributions. For basic use, start with
np.random.random()for floats between 0 and 1. - Generate a single random float with
np.random.random(). For example,single_float = np.random.random()returns a value like 0.3745401188473625. - Generate an array of random floats by passing a shape tuple. For a 1D array of 5 floats, use
np.random.random(5). For a 2D array (3 rows × 4 columns), usenp.random.random((3, 4)). - To generate random integers, use
np.random.randint(low, high, size). Thehighvalue is exclusive. For example,np.random.randint(1, 11, size=3)produces three integers between 1 and 10 (inclusive). - For reproducible results across runs, set a random seed before generating numbers:
np.random.seed(42). After this, subsequent calls (e.g.,np.random.random()) will yield the same sequence every time you run the code. - To sample from a normal (Gaussian) distribution, use
np.random.normal(loc=0.0, scale=1.0, size=None). For instance,np.random.normal(0, 1, 5)gives five values from a standard normal distribution (mean 0, standard deviation 1). - To sample from a uniform distribution over a specific interval, use
np.random.uniform(low=0.0, high=1.0, size=None). Example:np.random.uniform(-5, 5, size=(2, 3))returns a 2×3 array of floats between -5 and 5. - To sample *without replacement* from a given 1D array (e.g., shuffling a deck or selecting survey participants), use
np.random.choice(a, size=None, replace=True). Setreplace=Falseto avoid duplicates:np.random.choice([1, 2, 3, 4, 5], size=3, replace=False).
Common Mistakes
- Forgetting to import NumPy and calling
random()directly—Python’s built-inrandommodule behaves differently and lacks NumPy’s array support. - Misunderstanding the
highparameter inrandint: it’s exclusive. Usingrandint(1, 10)will never return 10; to include 10, userandint(1, 11). - Reusing the same seed unintentionally across script runs and expecting different results. If you set
np.random.seed(123)before every run, the sequence resets each time—remove or adjust the seed for varied runs. - Passing a negative number as the
sizeparameter, which raises aValueError. Always ensuresizeis non-negative (e.g., 0 is valid and returns an empty array). - Confusing
np.random.rand()(no parentheses needed for shape) withnp.random.random()(requires a tuple for multi-dimensional shapes).rand(3, 4)creates a 3×4 array, butrandom((3, 4))does the same—mixing syntax can cause confusion.
Tips
- Use
np.random.Generatorfor modern, flexible random number generation. Initialize once:rng = np.random.default_rng(), then callrng.random(),rng.integers(), etc. This is preferred over the legacy globalnp.randomfor large projects. - Save the generator instance to a variable for reproducibility:
rng = np.random.default_rng(seed=42). This avoids polluting the global random state and makes code easier to test. - Use
np.random.shuffle(x)to randomly reorder a NumPy array *in place*. For a list, convert it to an array first or userandom.shufflefrom Python’s built-in module. - For statistical work, prefer
np.random.default_rng().choice(..., replace=False)overnp.random.permutationfor clearer intent and better control over sampling. - Generate random booleans by comparing uniform floats to a threshold:
(np.random.random() < 0.5)returns True/False with 50% probability each. - Use
np.set_printoptions(precision=3)to control decimal places when printing arrays, improving readability.
Troubleshooting
If you encounter errors, follow these checks:
- ModuleNotFoundError: No module named 'numpy'—NumPy isn’t installed. Run
pip install numpy(orpip3if using Python 3). In Jupyter, use!pip install numpyin a cell. - TypeError: 'int' object is not iterable—you likely passed an integer instead of a tuple to
random()for multi-dimensional arrays. Usenp.random.random((3, 4)), notnp.random.random(3, 4). - ValueError: low >= high in
randint—double-check your bounds. For example,randint(10, 5)fails; ensure low < high. - ValueError: a must be 1-dimensional or an integer with
choice—if passing a list, convert it to a NumPy array first:np.random.choice(np.array(my_list), ...). - Reproducibility not working—verify the seed is set *before* any random calls and that no other libraries reset the global seed. Prefer using
default_rng(seed=...)instead ofnp.random.seed. - Unexpected performance slowdown—generating large arrays with
np.randomin a loop is slow. Instead, generate all samples at once:np.random.random((1000000,))instead of looping 1 million times.
Frequently Asked Questions
Can I generate random numbers between two specific values, say 5 and 15?
Yes. Use np.random.uniform(5, 15, size=n) for floats or np.random.randint(5, 16, size=n) for integers (note: 16 makes 15 inclusive).
How do I generate random numbers without duplicates?
Use np.random.choice with replace=False. Example: np.random.choice(100, size=10, replace=False) picks 10 unique integers from 0–99.
Is NumPy’s random truly random?
No—it’s pseudo-random. It uses deterministic algorithms that produce sequences appearing random. This is sufficient for simulations and data science. For cryptography, use Python’s secrets module instead.
Can I generate random numbers from a custom distribution?
Yes. Use np.random.choice with the p argument to specify probabilities. Example: np.random.choice([0, 1, 2], size=5, p=[0.7, 0.2, 0.1]) yields 0, 1, or 2 with those weights.
What’s the difference between np.random and numpy.random?
They’re the same—np.random is just the standard alias after import numpy as np. However, NumPy now recommends using np.random.default_rng() to create a generator instance for better performance and state management.
How do I generate random numbers for a specific distribution like Poisson?
Use np.random.poisson(lam=1.0, size=None). For example, np.random.poisson(3, size=4) generates four values from a Poisson distribution with mean 3.