numpy.random.rand() in Python

Last Updated : 13 Jan, 2026

numpy.random.rand() is a NumPy function used to generate random numbers between 0 and 1 and store them in an array of a specified shape. This basic example shows how to generate a single random value between 0 and 1 using numpy.random.rand().

Python
import numpy as np
x = np.random.rand()
print(x)

Output
0.2972517962001888

Explanation: np.random.rand() returns one random floating-point number between 0 and 1 when no arguments are passed.

Syntax

numpy.random.rand(d0, d1, ..., dn)

Parameters: d0, d1, ..., dn - Integers specifying the dimensions of the output array. If no arguments are given, a single float value is returned

Examples

Example 1: This example generates a one-dimensional array containing 5 random values between 0 and 1.

Python
import numpy as np
arr = np.random.rand(5)
print(arr)

Output
[0.17862818 0.70291472 0.78424777 0.15267243 0.69117054]

Explanation: np.random.rand(5) creates a 1D array of length 5 filled with random values between 0 and 1.

Example 2: This example creates a 2D array with 3 rows and 4 columns filled with random values.

Python
import numpy as np
arr = np.random.rand(3, 4)
print(arr)

Output
[[0.85658609 0.5904273  0.42261486 0.87244229]
 [0.47780515 0.82188824 0.8182546  0.01274018]
 [0.23222563 0.86268323 0.39799433 0.33220185]]

Explanation: np.random.rand(3, 4) generates a 3×4 matrix, where each element is a random value between 0 and 1.

Example 3: This example demonstrates how to generate a 3D array of shape (2, 2, 2) using random values.

Python
import numpy as np
arr = np.random.rand(2, 2, 2)
print(arr)

Output
[[[0.24843976 0.4158671 ]
  [0.73343447 0.05072488]]

 [[0.39851802 0.74778753]
  [0.43248647 0.89850875]]]

Explanation: np.random.rand(2, 2, 2) creates a three-dimensional array, where all values are randomly generated between 0 and 1.

Comment

Explore