Let’s say we want to create a NumPy array of a particular shape that is filled with random numbers. We can use the numpy.random.random() function for that purpose. For example, we can use the following Python code to create a NumPy array of shape (2, 3) that is filled with random floating point numbers.
import numpy a = numpy.random.random(size=(2, 3)) print(a)
As we know, numpy.random.random() function generates random numbers in the half-open interval [0.0, 1.0), i.e. the interval includes 0 but does not include 1. The size argument specifies the shape of the created NumPy array.
Here, we are creating a NumPy array that has 2 rows and 3 elements in each row. And each entry of the NumPy array is filled with floating point numbers in the half-open interval [0.0, 1.0).
So, the output of the mentioned program will be:
[[0.64224377 0.55904248 0.74415162] [0.87157522 0.20693246 0.17072933]]
Please note that we can also use the numpy.random.randint() function to fill the NumPy array with random integers. For example, we can use the following Python code to create a NumPy array of shape (2, 3) that is filled with random integers.
import numpy b = numpy.random.randint(low=1, high=100, size=(2, 3)) print(b)
Please note that the numpy.random.randint() function generates random integers within the half-open interval [low, high), where low indicates the lowest integer and high indicates the highest integer.
The size argument specifies the shape of the created NumPy array. Here, shape=(2, 3) means the created NumPy array will have 2 rows and 3 elements in each row.
So, the output of the mentioned program will be:
[[ 9 64 18] [47 79 69]]
0 Comments