Seite - 47 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 47 -
Text der Seite - 47 -
2.3 NumericalPythonArrays 47
True toFalse and vice versa. Continuing the preceding session with a few more
exampleswill illustrate thesepoints,
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 alterna-
tivelybewritten3 < x < 5. Itmayalsobeaddedthat thefinalbooleanexpression,
i.e.,not x == 4 is equivalent tox != 4 fromabove,whichmostof usfind easier
to read.
Wewillmeetbooleanexpressionsagainsoon,whenweaddresswhile loopsand
branchingin Chap.3.
2.3 NumericalPythonArrays
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 fromnumpy. The arrays will be of
typenumpy.ndarray, referred to asN-dimensionalarrays 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
arrayelements. All arrayelementsmust be of the same type, e.g., all integersor all
floatingpointnumbers.
2.3.1 ArrayCreationandArrayElements
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 xwith three real numbers, evenly
distributedon [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 tonumpy arrays, since they allow
moreefficientcomputations.Thus,wheneverwewrite“array”, it isunderstood tobeanumpyarray.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik