To generate uniform random numbers in Python, use the random.uniform(a, b) function from the built-in random module for floating-point values, or random.randint(a, b) for integers. For cryptographic or scientific applications, use secrets.randbelow() or numpy.random.uniform() respectively.
What Are Uniform Random Numbers?
A uniform random number is one drawn from a distribution where every value in a given range has an equal probability of being selected. In Python, this typically means a continuous uniform distribution over [a, b) (including a, excluding b) for floats, or a discrete uniform distribution over integers from a to b inclusive. Uniform randomness is the foundation for simulations, statistical sampling, games, and many machine learning algorithms.
Using the random Module
The standard library’s random module is the simplest way for most tasks. It uses the Mersenne Twister algorithm, which is deterministic but seeded by default from OS entropy. Key functions:
random.random()– returns a float in [0.0, 1.0)random.uniform(a, b)– returns a float in [a, b] (may include b due to rounding)random.randint(a, b)– returns an integer in [a, b] inclusiverandom.randrange(start, stop, step)– likerangebut random
Example:
import random
print(random.uniform(0, 10)) # e.g., 7.238491
print(random.randint(1, 6)) # e.g., 4
For reproducibility, set a seed: random.seed(42). This is crucial for debugging and testing.
Using NumPy for Bulk Generation
When you need many numbers quickly or in array form, numpy.random is far more efficient. It also offers more distribution control and better statistical properties for large-scale simulations.
import numpy as np
arr = np.random.uniform(0, 1, size=1000) # 1000 floats in [0,1)
ints = np.random.randint(0, 10, size=100) # 100 integers 0-9
NumPy’s default RNG is also Mersenne Twister, but you can use the newer Generator class with np.random.default_rng() for better algorithms like PCG64:
rng = np.random.default_rng(42)
vals = rng.uniform(0, 1, 10)
Cryptographically Secure Uniform Numbers
The random and numpy modules are not suitable for security purposes—they are predictable if the seed is known. For passwords, tokens, or any security-sensitive randomness, use the secrets module:
import secrets
secure_float = secrets.randbelow(1000) / 1000 # uniform in [0,1)
secure_int = secrets.randbelow(10) # 0-9
secure_choice = secrets.choice(['a', 'b', 'c'])
secrets uses OS-provided randomness, which is cryptographically strong.
How to Choose the Right Function
Your choice depends on the use case:
- Simple scripts, games, simulations:
random.uniformorrandom.randint. - Large arrays, scientific computing:
numpy.random.uniformorrng.uniform. - Security (passwords, tokens):
secretsmodule. - Reproducible experiments: Use
random.seedor a NumPyGeneratorwith a fixed seed.
Common Pitfalls and Misconceptions
One frequent mistake is assuming random.uniform(a, b) includes b. It may or may not due to floating-point rounding; the documentation says it can return b. For strict [a, b), use random.random() * (b - a) + a. Another misconception is that random.randint(a, b) is exclusive of b—it is inclusive. Also, never use random.random() for security; it is not unpredictable. Finally, be aware that the Mersenne Twister is not suitable for serious statistical work that requires high-dimensional independence; for that, consider numpy‘s PCG64 or other generators.
Performance and Alternatives
Generating millions of random numbers with random in a loop is slow. NumPy can be 10-100x faster because it generates arrays in C. For extreme performance, consider numba or Cython, but for most tasks NumPy suffices. There is also random.SystemRandom for a class-based interface to OS randomness, but secrets is simpler.
Frequently Asked Questions
How do I generate a random float between 0 and 1?
Use random.random() for a float in [0.0, 1.0), or numpy.random.rand() for an array. For a cryptographically secure version, use secrets.randbelow(10**6) / 10**6.
How do I generate a random integer in a range?
Use random.randint(a, b) for inclusive endpoints, or random.randrange(a, b) for exclusive b. In NumPy, numpy.random.randint(a, b) is exclusive of b, so be careful—it’s different from the standard library.
What is the difference between random.uniform and random.triangular?
random.uniform gives a uniform distribution where every value has equal probability. random.triangular gives a triangular distribution, where values near the mode are more likely. Use triangular when you need a bell-like shape without a full normal distribution.
Can I make the random numbers reproducible?
Yes. Call random.seed(42) before generating numbers to get the same sequence each run. For NumPy, create a generator with np.random.default_rng(42). For secrets, reproducibility is not possible by design—it’s meant to be unpredictable.
Why does random.uniform sometimes return b?
Due to floating-point rounding, the formula a + (b-a) * random() can round up to b. The documentation notes this. If you need to exclude b, use random.random() * (b - a) + a and accept it might still round to b in rare cases; alternative is to use numpy.random.uniform which also may include b.
Related
- Google Sheets UNIQUE Function: How It Works
- Google Sheets Scheduling Template: How to Build One
- Google Sheets Schedule Template Free? Yes, Here’s How
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Goal Seek in Excel: Step-by-Step InstructionsTo use Goal Seek in Excel for Microsoft 365 on Windows, select Data > What-If Analysis > Goal…
- Custom Cover Page in Word: Create and Add Your OwnTo add a custom cover page in Word, place a new page at the start of your document,…
- Excel Cell Won’t Move With Arrow Keys? Fixes That WorkIf an Excel cell will not move when you press an arrow key, first check whether Scroll Lock…
- Excel Worksheet vs CSV: Key Differences and When to Use EachAn Excel worksheet is a grid of cells inside an Excel workbook, while a CSV file is a…
- Copy in Excel and Paste as an Image: Step-by-StepTo copy cells in Excel as an image, select the range, choose Home > Copy ▼ > Copy…
- Excel Data Analysis: Tools, Steps, and LimitsYes. Excel can generate data analysis by summarizing tables, calculating results, finding patterns, and creating charts or reports;…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.