In this short guide, we will learn how to generate random float numbers within a specific range using Python's random and numpy modules. Whether you're simulating sensor data, creating test datasets, or building Monte Carlo simulations, generating random decimal numbers is essential for scientific computing, gaming, and data science applications.
Python provides multiple methods to generate random floats - from the built-in random.uniform() to NumPy's powerful random.uniform() for array generation.
1. Using random.uniform() for Single Random Floats
The random.uniform() function is the simplest way to generate a random float between two numbers, inclusive of the lower bound and exclusive of the upper bound.
import random
price = random.uniform(10.5, 99.99)
temperature = random.uniform(-5.0, 35.0)
discount = random.uniform(0.1, 0.5)
print(f"Random price: ${price:.2f}")
print(f"Temperature: {temperature:.1f}°C")
print(f"Discount rate: {discount:.2%}")
Output Result:
Random price: $67.43
Temperature: 18.2°C
Discount rate: 28.45%
How it works: The random.uniform(a, b) returns a random floating-point number N such that a <= N <= b. The :.2f formatting rounds to 2 decimal places, perfect for monetary values or measurements.
2. Generating Multiple Random Floats with List Comprehension
For batch generation of random floats, use list comprehension to create arrays of random values efficiently.
import random
sensor_readings = [random.uniform(20.0, 25.0) for _ in range(5)]
stock_prices = [random.uniform(100.0, 150.0) for _ in range(10)]
print(f"Sensor readings: {[f'{x:.2f}' for x in sensor_readings]}")
print(f"Average stock price: ${sum(stock_prices)/len(stock_prices):.2f}")
print(f"Price range: ${min(stock_prices):.2f} - ${max(stock_prices):.2f}")
Output Result:
Sensor readings: ['22.47', '23.81', '21.05', '24.32', '20.89']
Average stock price: $124.67
Price range: $103.21 - $148.92
Real-world application: This is ideal for testing algorithms, generating dummy datasets, or simulating real-world measurements like temperature sensors, stock prices, or scientific experiments.
3. Using NumPy for Fast Array Generation
For large-scale simulations or scientific computing, NumPy's random.uniform() generates arrays of random floats much faster than pure Python.
import numpy as np
prices = np.random.uniform(50.0, 200.0, size=1000)
coordinates = np.random.uniform(-180.0, 180.0, size=(100, 2))
print(f"Generated {len(prices)} prices")
print(f"Mean price: ${prices.mean():.2f}")
print(f"First 5 prices: ${prices[:5]}")
print(f"\nFirst 3 coordinates: {coordinates[:3]}")
Output Result:
Generated 1000 prices
Mean price: $124.89
First 5 prices: [167.32 89.45 156.78 92.11 143.67]
First 3 coordinates: [[-145.23 78.91]
[ 23.45 -167.34]
[ 89.12 -45.67]]
Performance advantage: NumPy is 10-100x faster for generating large arrays of random numbers, making it essential for machine learning, data science, and scientific simulations.
4. Practical Examples: Simulations and Testing
Here's how to use random floats in real-world scenarios like A/B testing, price simulations, and game development.
import random
def simulate_conversion_rate(visitors, base_rate=0.05, variance=0.02):
"""Simulate conversion rates for A/B testing"""
return [random.uniform(base_rate - variance, base_rate + variance)
for _ in range(visitors)]
def generate_product_prices(count, min_price=9.99, max_price=999.99):
"""Generate realistic product prices"""
return [round(random.uniform(min_price, max_price), 2) for _ in range(count)]
conversion_rates = simulate_conversion_rate(7)
product_catalog = generate_product_prices(5)
print(f"Simulated conversion rates: {[f'{x:.2%}' for x in conversion_rates]}")
print(f"Product prices: {['$' + str(x) for x in product_catalog]}")
Output Result:
Simulated conversion rates: ['4.23%', '6.78%', '5.12%', '3.89%', '6.45%', '4.91%', '5.67%']
Product prices: ['$456.78', '$123.45', '$789.01', '$234.56', '$567.89']
Common Use Cases
Financial Simulations: Generate stock prices, interest rates, portfolio returns
Game Development: Random damage values, spawn coordinates, item drop rates
Machine Learning: Creating synthetic datasets, noise injection, data augmentation
Scientific Computing: Monte Carlo simulations, random sampling, statistical analysis
Testing: Generating test data, load testing with random delays, fuzzing
Quick Reference
| Method | Use Case | Speed |
|---|---|---|
| random.uniform(a, b) | Single float | Fast |
| [random.uniform(...) for ...] | Small batches | Medium |
| np.random.uniform(a, b, n) | Large arrays | Very Fast |
Choosing the Right Method
- Single random float? → Use random.uniform() (Method 1)
- Small batch (< 100)? → Use list comprehension (Method 2)
- Large arrays (1000+)? → Use NumPy (Method 3)
- Reproducible results? → Set random.seed() first
For most scientific applications and data science work, NumPy is the preferred choice due to superior performance and integration with the scientific Python ecosystem.