numpy.random.rand() in Python

The numpy.random.rand() method creates array of specified shape with random values. This method mainly used to create array of random values.

Basic Syntax

numpy.random.rand() in Python function overview
numpy.random.rand() in Python function overview

Following is the basic syntax for numpy.random.rand() method:

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

And the parameters are:

Parameter Description
d0, d1, d2, …, dn [integer,optional] Enter dimentions of the required array. If no argument is specified single python value will be returned.

Returns

This function returns array of random values with specified shape.

Example

Following are the examples for generating 1D, 2D and 3D arrays.

Example 1: 1D array

# Python Program for numpy.random.rand() method 
   
import numpy as np 
   
# Generating 1 Dimentional array 
array = np.random.rand(10) 
print("1D random values array : \n", array); 

The output should be:

1D random values array :
[0.23190488, 0.53400471, 0.20537607, 0.46551987, 0.12542115,
0.68377143, 0.41102983, 0.40300743, 0.86667939, 0.96476523]

Example 2: 2D array

# Python Program for numpy.random.rand() method 
   
import numpy as np 
   
# Generating 2 Dimentional array 
array = np.random.rand(2,2) 
print("2D random values array : \n", array); 

The output should be:

2D random values array
[[ 0.09697723, 0.4666872 ],
[ 0.06225284, 0.41580441]]

Example 3: 3D array

# Python Program for numpy.random.rand() method 
   
import numpy as np 
   
# Generating 3 Dimentional array 
array = np.random.rand(3,3,3) 
print("3D random values array : \n", array); 

The output should be:

3D random values array :
[[[5.52075828e-01, 9.11790914e-01, 4.00528404e-01],
[8.08595587e-01, 2.54659725e-02, 3.73636769e-01],
[3.69575988e-02, 7.91622346e-01, 7.07231348e-01]],
[[3.46851455e-02, 8.27783769e-01, 7.13739325e-01],
[9.06570460e-01, 1.75582354e-02, 2.19411517e-04],
[8.08957851e-01, 8.74399677e-02, 6.27145619e-01]],
[[9.73312118e-01, 6.74844165e-01, 8.49714391e-02],
[7.28513937e-01, 3.14178426e-01, 4.73964127e-01],
[5.82489203e-01, 5.17546522e-01, 5.59685367e-01]]]