The np.random.uniform()
function draws random numbers from a continuous uniform distribution.
import numpy as np
np.random.uniform()
# Expected result like...
# 0.20156508227392989
Basic usage
By default, the range is [0, 1)
and the function returns a scalar. But this can be adjusted with the low
, high
and size
arguments. For example, to generate 3 random numbers between -10 and 10:
np.random.uniform(-10, 10, size=3)
# Expected result like...
# array([ 6.64893079, -9.70234671, 4.01869664])
As a convention, I usually pass in low
and high
as positional arguments and set size as a keyword argument, but this is just my own style preference.
Multi-dimensional arrays
If you want a random array with shape (2, 2)
, you can pass a tuple in for size
:
np.random.uniform(-10, 10, size=(2, 2))
# Expected result like...
# array([[-4.22106242, -7.85748055],
# [ 1.32769555, -3.05958937]])
Data types
Although many NumPy functions accept a dtype
argument, np.random.uniform()
will always return np.float64
values, either as a single scalar or as an np.ndarray
. But if you want a different data type, you can use the astype()
method on the result:
np.random.uniform(size=2).astype("float32")
# Expected result like...
# array([0.02816657, 0.7264831 ], dtype=float32)
Seeds
If you want to set the seed for the random number generator, you can use np.random.seed()
:
np.random.seed(10)
np.random.uniform()
# Expected result (every time)
# 0.771320643266746
This is an important strategy for testing non-deterministic code.
As a final note, the official NumPy docs now suggest using a default_rng()
random number generator instead of np.random.uniform()
. I don’t think this is super common yet, but it is something to watch out for.