NumPy Uniform Distribution
The uniform distribution models a random variable where every value within a defined range is equally likely to occur, and NumPy's random.uniform() lets you sample from it directly.
What Is a Uniform Distribution?
In a uniform distribution, every outcome between a lower bound and an upper bound has exactly the same probability of being chosen. Unlike the normal distribution, there is no peak or bias toward the center -- a histogram of enough uniform samples looks flat, like a rectangle, rather than bell-shaped.
The random.uniform() Method
NumPy exposes this distribution through numpy.random.uniform(low=0.0, high=1.0, size=None). The low argument is the inclusive lower bound, high is the exclusive upper bound, and size controls how many values (and in what shape) are returned. If size is omitted, a single float is returned.
Example
import numpy as np
# A single random float between 0 and 1
value = np.random.uniform()
print(value)
# A single random float between 5 and 10
value = np.random.uniform(5, 10)
print(value)
# An array of 6 random floats between 0 and 100
values = np.random.uniform(0, 100, size=6)
print(values)Shaping the Output with size
The size parameter accepts an integer for a 1-D array or a tuple for a multi-dimensional array. This makes it easy to build a whole matrix of uniformly distributed values in one call, which is useful for simulations, initializing weights, or generating synthetic test data.
Example
import numpy as np
# A 3x4 matrix of values between -1 and 1
matrix = np.random.uniform(-1, 1, size=(3, 4))
print(matrix)
print(matrix.shape)
# The theoretical mean of a uniform(low, high) distribution is (low + high) / 2
print(matrix.mean())- Every value in [low, high) has equal probability density.
- The theoretical mean is (low + high) / 2.
- The theoretical variance is (high - low)**2 / 12.
- Increasing size makes the sample mean and histogram converge toward the theoretical values.
- The interval is half-open: low can appear, high never will.
Example
import numpy as np
np.random.seed(0)
n = 100000
x = np.random.uniform(-1, 1, n)
y = np.random.uniform(-1, 1, n)
inside_circle = (x**2 + y**2) <= 1
pi_estimate = (inside_circle.sum() / n) * 4
print(pi_estimate)Exercise: NumPy Uniform Distribution
What best describes the probability density of a uniform distribution?