We use np.random.rand() to create arrays filled with random numbers between 0 and 1. This helps us test ideas or simulate real-world data when we don't have actual data.
np.random.rand() and random arrays in NumPy
import numpy as np # Create a random array with shape (d1, d2, ..., dn) random_array = np.random.rand(d1, d2, ..., dn)
The arguments d1, d2, ..., dn are the dimensions of the array you want.
The numbers generated are floats between 0 (inclusive) and 1 (exclusive).
import numpy as np # 1D array with 5 random numbers array_1d = np.random.rand(5) print(array_1d)
import numpy as np # 2D array with 3 rows and 4 columns array_2d = np.random.rand(3, 4) print(array_2d)
import numpy as np # Edge case: zero size array empty_array = np.random.rand(0) print(empty_array)
import numpy as np # 3D array with shape (2, 1, 3) array_3d = np.random.rand(2, 1, 3) print(array_3d)
This program creates two different 2D random arrays with 2 rows and 3 columns each. It prints both arrays so you can see the random numbers generated.
import numpy as np # Create a 2D random array with 2 rows and 3 columns random_array_before = np.random.rand(2, 3) print("Random array before:") print(random_array_before) # Create another random array with the same shape random_array_after = np.random.rand(2, 3) print("\nRandom array after:") print(random_array_after)
Time complexity: Generating random numbers with np.random.rand() is very fast and runs in O(n) where n is the total number of elements.
Space complexity: The space used is proportional to the size of the array you create.
Common mistake: Forgetting that the numbers are always between 0 and 1, so if you want other ranges, you need to scale or shift the numbers.
When to use: Use np.random.rand() when you want random floats between 0 and 1. For other distributions or integer random numbers, use other functions like np.random.randint() or np.random.normal().
np.random.rand() creates arrays filled with random floats between 0 and 1.
You specify the shape by giving dimensions as arguments.
It is useful for testing, simulations, and initializing random data.