What is the numpy.random.rand() Method

Numpy.random.rand() method “creates an array of specified shapes and fills it with random values.”

Syntax

numpy.random.rand(dimension) 

Parameters

dimension: It takes one argument, which indicates the dimension of the ndarray with random values.

Return Value

The rand() function returns an nd-array with a given dimension filled with random values.

Example 1: How to Use np.random.rand() Method

# importing numpy
import numpy as np

# Now creating an 1D array of size 10
arr = np.random.rand(10)

print("Values of 1D array is:\n", arr)
print("Shape of the array is : ", np.shape(arr))

# Creating of size 5
arr2 = np.random.rand(5)
print("Values of the array is:\n ", arr2)
print("Shape of the array is : ", np.shape(arr2))

Output

Values of 1D array is:
 [0.17352283 0.16893341 0.76386692 0.03138259 0.59792538 0.76615978
 0.84131927 0.61328718 0.32773058 0.65744193]

Shape of the array is : (10,)

Values of the array is:
 [0.90645146 0.83536319 0.29311148 0.2786733 0.87616911]
Shape of the array is : (5,)

Example 2: Working with a 2D array

#importing numpy
import numpy as np

#Now creating an 2D array of size 4x5
arr=np.random.rand(4,5)

print("Values of 2D array is:\n",arr)
print("Shape of the array is : ",np.shape(arr))

#Creating of size 5x5
arr2=np.random.rand(5,5)
print("Values of the array is:\n ",arr2)
print("Shape of the array is : ",np.shape(arr2) )

Output

Values of 2D array is:
 [[0.28861984 0.18593293 0.45034183 0.3699019 0.89226622]
 [0.98189518 0.85439992 0.06126254 0.13031828 0.21441592]
 [0.93145627 0.7457769 0.34015265 0.91147038 0.09517888]
 [0.20201291 0.05616537 0.23150696 0.17963964 0.15687614]]
Shape of the array is : (4, 5)
Values of the array is:
 [[0.39721576 0.7976625 0.93283862 0.42401951 0.84877493]
 [0.23814044 0.08125397 0.0431911 0.75650221 0.79033326]
 [0.59390514 0.0592595 0.72867553 0.12893031 0.67127664]
 [0.83742068 0.6945678 0.8227099 0.97034151 0.54721918]
 [0.77069907 0.44371671 0.76421675 0.58487264 0.79122344]]
Shape of the array is : (5, 5)

Example 3: Randomly constructing a 3D array

import numpy as np

arr = np.random.rand(3, 3 ,3)
print(arr)

Output

[[[0.38006532 0.2043177 0.04151669]
 [0.08123459 0.00396446 0.45554039]
 [0.43268626 0.42675334 0.40112589]]

 [[0.7407576 0.99920578 0.05148135]
 [0.43728199 0.20692016 0.47393593]
 [0.06295439 0.70542709 0.32708993]]

 [[0.77695208 0.93483407 0.8789653 ]
 [0.09310584 0.70866755 0.90443876]
 [0.15779272 0.29006161 0.82855443]]]
That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.