Numpy.random.rand() method creates an array of specified shape filled with random samples drawn from a uniform distribution over the half-open interval [0, 1).
If you don’t define any dimensions, it returns a single Python float.
If you specify the dimensions, it returns an ndarray of shape (d0, d1, …, dn).
import numpy as np random_arr = np.random.rand(5) print(random_arr) # Output: [0.41811807 0.39197461 0.00194327 0.82596342 0.60779158]
In this code, we are generating an array with 5 random values between 0 and 1.
Syntax
numpy.random.rand(d0, d1, ..., dn)
Parameters
Argument | Description |
d0, d1, …, dn (optional, int) | It represents the dimensions of the returned array. |
Single random float generator
If you don’t pass any argument to the np.random.rand() function, it returns a single random float value.
import numpy as np single_value = np.random.rand() print(single_value) # Output: 0.859010523481361
The output value is between 0 and 1.
Generating 2D Array
Let’s generate a 2D array by passing two arguments to this method.
import numpy as np arr_2d = np.random.rand(2, 3) print(arr_2d) # Output: # [[0.05351508 0.94558385 0.80291724] # [0.60434141 0.16902043 0.14530189]]
Reproducibility with Seed
If you want consistent results on each run, you can set the seed and then generate the random number array, ensuring it remains the same each time.
To set the seed, use the np.random.seed() method.
import numpy as np np.random.seed(21) arr_2d = np.random.rand(2, 2) print(arr_2d) # Output: # [[0.04872488 0.28910966] # [0.72096635 0.02161625]]
Now, if you run the above program on your computer, it will display the exact random numbers as I do because we have now set the seed to 21.
Empty shape
If you pass 0 dimensions, it returns an empty 1D array with shape (0,).
import numpy as np empty_array = np.random.rand(0) print(empty_array) # Output: [] print(arr.shape) # Output: (0,)
That’s all!