48
2 A Few More Steps
In [4]: type(x)
# check type of array as a whole
Out[4]: numpy.ndarray
In [5]: type(x[0])
# check type of array element
Out[5]: numpy.float64
The line x = linspace(0, 2, 3) makes Python reserve, or allocate, space in
memory for the array produced by linspace. With the assignment, x becomes
a reference to the array object from linspace, i.e. x becomes the “name of the
array”. The array will have three elements with names x[0], x[1] and x[2], where
the bracketed numbers are referred to as indices (note that when reading, we say “x
of zero” to x[0], “x of one” to x[1], and so on).
Observe that the indexing starts with 0, so that an array with n elements will have
n-1 as the last index. We say that Python has zero based indexing, which differs
from one based indexing where array indexing starts with 1 (as, e.g., in Matlab). In
x, the value of x[0] is 0.0, the value of x[1] is 1.0 and, finally, the value of x[2]
is 2.0. These values are given by the printout array([ 0., 1., 2.]) above.
With the command type(x), we confirm that the array object named x has type
numpy.ndarray. Note that, at the same time, the individual array elements refer to
objects with another type. We see this from the very last command, type(x[0]),
which makes Python respond with numpy.float64 (being just a certain float data
type in NumPy 9 ).
If we continue the previous dialogue with a few lines, we can also demonstrate
that use of individual array elements is straight forward:
In [4]: sum_elements = x[0] + x[1] + x[2]
In [5]: sum_elements
Out[5]: 3.0
In [6]: product_2_elements = x[1]*x[2]
In [7]: product_2_elements
Out[7]: 2.0
In [8]: x[0] = 5.0
# overwrite previous value
In [9]: x
Out[9]: array([ 5., 1., 2.])
The Zeros Function There are other common ways to generate arrays too. One
way is to use another numpy function named zeros, which (as the name suggests)
may be used to produce an array with zeros. These zeros can be either floating
point numbers or integers, depending on the arguments provided when zeros is
called. 10 Often, the zeros are overwritten in a second step to arrive at an array with
the numbers actually wanted.
9 You may check out the many numerical data types in NumPy at https://docs.scipy.org/
doc/numpy-1.13.0/user/basics.types.html.
10 https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.zeros.html.
Précédent

- 70/350

Suivant