How to generate a matrix of random floats with numpy ?

Published: February 19, 2023

Tags: Python; Numpy;

DMCA.com Protection Status

Using the NumPy library, it is possible to create a matrix of random floats:

Create a 1D matrix with n random floats

This can be done using the np.random module and its function random_sample().

import numpy as np

n = 10

data = np.random.random_sample(n)

This code will produce values that are evenly distributed between 0 and 1.

array([0.95511311, 0.74047589, 0.68174737, 0.7318436 , 0.70291076,
       0.17197878, 0.59607566, 0.42274757, 0.58774713, 0.29854085])

Create a matrix of random floats for a given shape

To create a matrix of random floats, simply specify the desired shape of the resulting array. For example:

data = np.random.random_sample((5,3))

will generate for example

array([[0.47, 0.17, 0.01],
       [0.59, 0.07, 0.9 ],
      [0.98, 0.63, 0.44],
       [0.59, 0.31, 0.63],
       [0.35, 0.48, 0.43]])

Additional features

Generate random floats between [a,b]:

a = -20
b = 100

data = np.random.random_sample(20) * ( b - a ) + a

gives for example

array([ 72.66937232,   3.84588178, -19.33734595,  77.85537141,
        64.82288126,  67.48086016,  72.5524416 , -11.11464179,
        23.01588743,  -6.09571286,  83.57241111,  54.79577522,
        19.70776298, -12.37299797,  17.31787861,  19.02199864,
        67.5527414 ,  56.50689656,  86.46552911,  36.66579102])

Generate always same random floats:

To do that a solution is to use a seed:

np.random.seed(42)

data = np.random.random_sample(10)

will always return same random numbers:

 array([0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864,
       0.15599452, 0.05808361, 0.86617615, 0.60111501, 0.70807258])

Round random floats

To do that a solution is to use the numpy function around():

For example

data = np.random.random_sample((5,3))

gives

array([[0.47422826, 0.16659521, 0.0104256 ],
       [0.59352088, 0.07216889, 0.89524555],
       [0.98402745, 0.6329296 , 0.43614741],
       [0.59215665, 0.30657867, 0.62781343],
       [0.34791008, 0.47968316, 0.42866502]])

Then

np.around(data,2)

gives

array([[0.47, 0.17, 0.01],
       [0.59, 0.07, 0.9 ],
       [0.98, 0.63, 0.44],
      [0.59, 0.31, 0.63],
       [0.35, 0.48, 0.43]])

References