Array generators
Of course, you can first create a list like previously and then convert it into an array. However, this is not very efficient on the one hand and not particularly convenient on the other. Here, we get to know the most common methods for generating arrays of certain properties.
Sequences
We have already learnt about the built-in function range
, which generates a sequence of numbers. In numpy
there are arange
(array range), linspace
(linearly spaced), and logspace
(logarithmically spaced), each of which generates a sequence of numbers.
np.arange(4) # array([0, 1, 2, 3])
np.arange(0, 4, 1) # array([0, 1, 2, 3])
The arguments of arange
are the same as for range()
. Unlike there, however, decimal numbers are possible as arguments. If an integer is passed, the array elements are also integers. If a decimal number is passed, the array elements are also decimal numbers.
np.arange(0, 4, 1) # array([0, 1, 2, 3])
np.arange(0, 4, 1.) # array([0., 1., 2., 3.])
While arange
generates a sequence based on the step size, linspace
generates an array based on the number of steps. With linspace
the entries have a constant distance to each other. With logspace
, the entries are distributed logarithmically.
np.linspace(0, 4, 5) # array([0., 1., 2., 3., 4.])
np.logspace(0, 1, 3) # array([1., 3.16227766, 10.])
Structured arrays
Equations often contain matrices that have a certain structure. The identity matrix, for example, can be created as follows:
np.identity(3) # array([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
The only argument here is the size of the matrix. We obtain the zero matrix with:
np.zeros((3, 3)) # array([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]])
If the diagonal is known, you can also create the diagonal matrix:
np.diag([1, 2, 3]) # array([[1, 0, 0],
# [0, 2, 0],
# [0, 0, 3]])
The same function returns the diagonal if the matrix is passed as an argument:
np.diag(np.identity(3)) # array([1., 1., 1.])
Random numbers
In many places, (pseudo-)random numbers allow an elegant solution to problems. numpy.random
contains a variety of functions to generate random numbers. The functions are sorted according to the distribution from which they are drawn.
np.random.uniform() # A number between 0 and 1
np.random.normal() # A number from a normal distribution
The functions can also generate whole arrays with random numbers:
np.random.uniform(size=3) # array([0.01460819, 0.26540185, 0.39614082])
np.random.uniform(size=(2,3)) # array([[0.62304467, 0.30562049, 0.220623 ],
# [0.59263397, 0.55564913, 0.01394508]])
size
corresponds to the size of the array to be generated, i.e. what you would expect in array.shape
.