2.3 Numerical Python Arrays
47
True to False and vice versa. Continuing the preceding session with a few more
examples will illustrate these points,
In [9]: x < 5 and x > 3
# x less than 5 AND x larger than 3
Out[9]: True
In [10]: x == 5 or x == 4
# x equal to 5 OR x equal to 4
Out[10]: True
In [11]: not x == 4
# not x equal to 4
Out[11]: False
The first of these compound expressions, i.e., x < 5 and x > 3, could alternatively be written 3 < x < 5. It may also be added that the final boolean expression,
i.e., not x == 4 is equivalent to x != 4 from above, which most of us find easier
to read.
We will meet boolean expressions again soon, when we address while loops and
branching in Chap. 3.
2.3 Numerical Python Arrays
We have seen simple use of arrays before, in ball_plot.py (Sect. 1.5), when
the height of a ball was computed a thousand times. Corresponding heights and
times were handled with arrays y and t, respectively. The kind of arrays used in
ball_plot.py is the kind we will use in this book. They are not part of standard
Python, 8 however, so we import what is needed from numpy. The arrays will be of
type numpy.ndarray, referred to as N-dimensional arrays in NumPy.
Arrays are created and treated according to certain rules, and as a programmer,
you may direct Python to compute and handle arrays as a whole, or as individual
array elements. All array elements must be of the same type, e.g., all integers or all
floating point numbers.
2.3.1 Array Creation and Array Elements
We saw previously how the linspace function from numpy could be used to
generate an array of evenly distributed numbers from an interval [a, b]. As a quick
reminder, we may interactively create an array x with three real numbers, evenly
distributed on [0, 2]:
In [1]: from numpy import linspace
In [2]: x = linspace(0, 2, 3)
In [3]: x
Out[3]: array([ 0., 1., 2.])
8 Standard Python does have an array object, but we will stick to numpy arrays, since they allow
more efficient computations. Thus, whenever we write “array”, it is understood to be a numpy array.
Précédent

- 69/350

Suivant