How to Generate Random Numbers Between 0 and 1 in Python?

In this tutorial, I will explain how to generate random numbers between 0 and 1 in Python. As a Python developer, I recently faced a challenge where I needed to simulate random events for a project based in New York City. After researching and testing different methods, I found several effective solutions that I will share with you in this article.

Generate Random Numbers Between 0 and 1 in Python

Python provides various ways to achieve this task. Let us see some important methods.

Read How to Get the Index of an Element in a List in Python?

Method 1. Use the random Module

Python’s random module provides various methods to generate random numbers. The most straightforward method to generate a random number between 0 and 1 is using random.random().

Example: Basic example

Here’s a simple example of generating a random number between 0 and 1:

import random

random_number = random.random()
print(random_number)

Output:

0.8420634044924983

I have executed the above example code and added the screenshot below.

Random Numbers Between 0 and 1 in Python

Example: Simulate Customer Arrivals

Imagine you are simulating customer arrivals at a coffee shop in Seattle. Each customer arrives at a random time between 0 and 1 hour.

import random

def simulate_customer_arrivals(num_customers):
    arrivals = [random.random() for _ in range(num_customers)]
    return arrivals

num_customers = 10
arrival_times = simulate_customer_arrivals(num_customers)
print(arrival_times)

Output:

[0.4940847145074486, 0.56179081905871, 0.36514752057335853, 0.6874942408355086, 0.44547457403119617, 0.06815249575323912, 0.7703119940858268, 0.8877232167616693, 0.8005425761537924, 0.7538029751025732]

I have executed the above example code and added the screenshot below.

Generate Random Numbers Between 0 and 1 in Python

In this example, simulate_customer_arrivals generates a list of random arrival times for 10 customers.

Check out How to Iterate Through a List in Python?

Method 2. Use uniform() for Custom Ranges

If you need a random number within a specific range, you can use the uniform(a, b) function, which returns a random floating-point number between a and b.

Example: Generate a Random Temperature

Let’s generate a random temperature between 60°F and 100°F, which might be useful for simulating weather conditions in Miami.

import random

temperature = random.uniform(60, 100)
print(f"The random temperature is {temperature:.2f}°F")

Output:

The random temperature is 60.26°F

I have executed the above example code and added the screenshot below.

How to Generate Random Numbers Between 0 and 1 in Python

This code will output a temperature between 60 and 100 degrees Fahrenheit, such as 82.34°F.

Read How to Select Items from a List in Python?

Method 3. Use random.seed() Function

For reproducibility, especially in testing or debugging, you can seed the random number generator using random.seed(). This ensures that the same sequence of random numbers is generated every time the program runs.

Example: Reproducible Results

import random

random.seed(42)
print(random.random())  
print(random.random())  

Output:

0.6394267984578837
0.025010755222666936

I have executed the above example code and added the screenshot below.

Random Numbers Between 0 and 1 in Python Use random.seed() Function

By seeding with 42 , the same random numbers are generated each time.

Check out How to Create an Empty Tuple in Python?

Method 4. Generate Multiple Random Numbers

To generate multiple random numbers efficiently, you can use list comprehensions or the random.sample() method.

Example: List Comprehension

import random

random_numbers = [random.random() for _ in range(5)]
print(random_numbers)

This code generates a list of 5 random numbers between 0 and 1.

Example: Use random.sample()

import random

random_numbers = random.sample([i/100.0 for i in range(100)], 5)
print(random_numbers)

This code generates 5 unique random numbers from a list of numbers between 0.0 and 1.0.

Read How to Access Tuple Elements in Python?

Advanced Techniques with NumPy

For more advanced applications, such as large-scale simulations or machine learning, the numpy library provides efficient methods for generating random numbers.

Example: Use NumPy

import numpy as np

random_numbers = np.random.rand(5)
print(random_numbers)

This code generates an array of 5 random numbers between 0 and 1 using NumPy.

Check out How to Print a Tuple in Python?

Application: Simulate Stock Prices

Let’s simulate daily stock price changes for a company based in San Francisco. We’ll use random numbers to model the daily percentage change in stock price.

import random

def simulate_stock_prices(start_price, days):
    prices = [start_price]
    for _ in range(days):
        daily_change = random.uniform(-0.02, 0.02)  # Simulate -2% to +2% daily change
        new_price = prices[-1] * (1 + daily_change)
        prices.append(new_price)
    return prices

start_price = 100  # Starting stock price
days = 30  # Number of days to simulate
stock_prices = simulate_stock_prices(start_price, days)

print(stock_prices)

In this example, we simulate 30 days of stock prices with random daily changes between -2% and +2%.

Check out How to Check if a Tuple is Empty in Python?

Conclusion

In this tutorial, I have explained how to generate random numbers between 0 and 1 in Python. I covered random module, uniform() method, random.seed() method and generating multiple random numbers using list comprehension and random.sample(). I also covered advanced techniques with Numpy and a real-time application.

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.