Python NumPy Random: 6 Ways to Generate Random Numbers

Working with random numbers is a common task in Python, especially when doing data analysis or building simulations. As someone who has worked extensively with NumPy for over a decade, I’ve found its random number generation capabilities to be highly useful and flexible.

In this tutorial, I’ll show you how to generate random numbers between specific values in NumPy, based on my experience using these functions in real-world applications.

Whether you’re simulating stock market data, creating test datasets, or building machine learning models, these techniques will help you generate the random data you need.

Python NumPy Random

Let me explain to you the different ways to generate random numbers in Python NumPy.

Read Python Program to Find the Smallest Element in a NumPy Array

1. Use np.random.uniform() for Random Floats

The most common way to generate random floating-point numbers between two values is using Python NumPy’s random.uniform() function.

Here’s how you can use it:

# Importing numpy module
import numpy as np

# Generating 5 random numbers between 0 and 1
random_numbers = np.random.uniform(0, 1, size=5)

# Printing the generated numbers
print(random_numbers)

This will output something like:

[0.37584874 0.17402496 0.58932746 0.02499468 0.63162676]

You can see the output in the screenshot below.

numpy random between two numbers

The uniform() function takes three parameters:

  • low: The lower boundary (inclusive)
  • high: The upper boundary (exclusive)
  • size: The shape of the output array

For example, if you need random numbers between 10 and 50:

# Generating 5 random numbers between 10 and 50
random_numbers = np.random.uniform(10, 50, size=5)
print(random_numbers)

This might output:

[27.39483921 45.82749103 18.57293741 32.91047582 11.83947293]

Check out Repeat Arrays N Times in Python NumPy

2. Use np.random.randint() for Random Integers

When working with data that requires integer values, I typically use the random.randint() function in Python. This is particularly useful for simulations involving discrete quantities.

Here’s how to generate random integers between two values:

# Importing numpy module
import numpy as np

# Generating 10 random integer values between 1 and 100
random_integers = np.random.randint(1, 101, size=10)

# Printing the generated integers
print(random_integers)

This might produce:

[39  6 25 15 31 50 92 93  3 78]

You can see the output in the screenshot below.

numpy random number between 0 and 1

The parameters for randint() are:

  • low: The lowest (inclusive) integer in the range
  • high: The highest (exclusive) integer in the range
  • size: The shape of the output array

Note that the upper bound is exclusive, so if you want to include 100, you need to use 101 as the upper bound.

Read Python NumPy Not Found: Fix Import Error

3. Use np.random.rand() for Multi-Dimensional Arrays

Sometimes I need to generate random arrays with specific dimensions. A Python random.rand() function is perfect for this, creating arrays filled with random values between 0 and 1.

# Importing numpy module
import numpy as np

# Generating a 3x3 matrix of random numbers between 0 and 1
random_matrix = np.random.rand(3, 3)

# Printing the generated matrix
print(random_matrix)

This will output a 3×3 matrix like:

[[0.33057432 0.53143532 0.54692448]
 [0.03514944 0.25393999 0.10267924]
 [0.98216077 0.60960381 0.55855537]]

You can see the output in the screenshot below.

use numpy to generate a random number

To generate a matrix with values in a different range, you can scale and shift the result:

# Generating a 2x2 matrix with values between 5 and 15
matrix = 10 * np.random.rand(2, 2) + 5
print(matrix)

Check out Create a Matrix in Python

4. Use np.random.normal() for Normal Distribution

When working with statistical models, I often need random numbers from a normal (Gaussian) distribution. This is especially common in financial modeling and machine learning applications.

# Generating 1000 values from a normal distribution with mean=0 and std=1
normal_values = np.random.normal(0, 1, 1000)

# Computing some statistics
mean = np.mean(normal_values)
std = np.std(normal_values)

print(f"Mean: {mean:.4f}, Standard Deviation: {std:.4f}")

The parameters for normal() are:

  • loc: The mean of the distribution (default: 0.0)
  • scale: The standard deviation of the distribution (default: 1.0)
  • size: The shape of the output array

This method is particularly useful for simulating stock market returns or noise in signal processing.

Read Create a Python Empty Matrix

Set a Random Seed for Reproducibility

When developing and testing code, I always set a random seed to ensure reproducibility. This way, I get the same “random” numbers each time I run the code.

# Setting a random seed
np.random.seed(42)

# Generating random numbers
random_values = np.random.rand(5)
print("First run:", random_values)

# Setting the same seed again
np.random.seed(42)

# Generating random numbers again
random_values_2 = np.random.rand(5)
print("Second run:", random_values_2)

# They will be identical
print("Are they the same?", np.array_equal(random_values, random_values_2))

This is essential for debugging and when sharing code with colleagues.

Check out NumPy Reset Index of an Array in Python

Use np.random.choice() for Random Sampling

Sometimes I need to randomly sample from a specific set of values. The random.choice() function is perfect for this:

# Creating an array of US states
states = np.array(['California', 'Texas', 'Florida', 'New York', 'Illinois'])

# Randomly selecting 3 states (with replacement)
selected_states = np.random.choice(states, size=3)
print(selected_states)

# Randomly selecting 3 states (without replacement)
selected_states_no_repeat = np.random.choice(states, size=3, replace=False)
print(selected_states_no_repeat)

This is particularly useful for randomized experiments or when creating test datasets.

NumPy’s random number generation functions offer tremendous flexibility for generating various types of random data. Whether you need uniform distributions, normal distributions, or random sampling, NumPy has you covered.

In my years of experience with data analysis and modeling, I’ve found these functions to be essential tools in my Python toolkit. The methods I’ve shared above should cover most scenarios you’ll encounter when working with random numbers in NumPy.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.