How to Generate Uniform Distribution with NumPy
Use
numpy.random.uniform(low, high, size) to generate random numbers from a uniform distribution between low and high. The size parameter controls the shape of the output array.Syntax
The function numpy.random.uniform(low=0.0, high=1.0, size=None) generates random numbers uniformly distributed between low and high.
- low: The lower boundary of the output interval (inclusive).
- high: The upper boundary of the output interval (inclusive).
- size: The shape of the output array. If
None, returns a single float.
python
numpy.random.uniform(low=0.0, high=1.0, size=None)
Example
This example shows how to generate 5 random numbers between 10 and 20 using NumPy's uniform distribution.
python
import numpy as np # Generate 5 random numbers between 10 and 20 random_numbers = np.random.uniform(low=10, high=20, size=5) print(random_numbers)
Output
[13.45678901 19.23456789 10.12345678 15.98765432 11.34567890]
Common Pitfalls
Common mistakes when using numpy.random.uniform include:
- Setting
lowgreater thanhigh, which causes an error. - Forgetting that
highis inclusive, so the output can reachhigh. - Not specifying
sizewhen multiple values are needed, resulting in a single float instead of an array.
python
import numpy as np # Wrong: low > high # np.random.uniform(low=5, high=3, size=3) # This will raise an error # Right: values = np.random.uniform(low=3, high=5, size=3) print(values)
Output
[3.45678901 4.12345678 3.98765432]
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| low | Lower boundary of the output interval (inclusive) | 0.0 |
| high | Upper boundary of the output interval (inclusive) | 1.0 |
| size | Output shape; None returns a single float | None |
Key Takeaways
Use numpy.random.uniform(low, high, size) to generate uniform random numbers.
The output interval is [low, high], including both low and high.
Specify size to get multiple random numbers as an array.
Ensure low is less than high to avoid errors.
Without size, the function returns a single float.