0
0
NumPydata~5 mins

np.random.rand() and random arrays in NumPy

Choose your learning style9 modes available
Introduction

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.

When you want to simulate random data for testing a model.
When you need random numbers to fill an array for experiments.
When you want to create random samples for a game or simulation.
When you want to initialize weights randomly in machine learning.
When you want to practice working with arrays and randomness.
Syntax
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).

Examples
This creates a 1D array with 5 random numbers between 0 and 1.
NumPy
import numpy as np

# 1D array with 5 random numbers
array_1d = np.random.rand(5)
print(array_1d)
This creates a 2D array (matrix) with 3 rows and 4 columns filled with random numbers.
NumPy
import numpy as np

# 2D array with 3 rows and 4 columns
array_2d = np.random.rand(3, 4)
print(array_2d)
This creates an empty array because the size is zero.
NumPy
import numpy as np

# Edge case: zero size array
empty_array = np.random.rand(0)
print(empty_array)
This creates a 3D array with 2 blocks, each having 1 row and 3 columns.
NumPy
import numpy as np

# 3D array with shape (2, 1, 3)
array_3d = np.random.rand(2, 1, 3)
print(array_3d)
Sample Program

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.

NumPy
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)
OutputSuccess
Important Notes

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().

Summary

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.