Seite - 49 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 49 -
Text der Seite - 49 -
2.3 NumericalPythonArrays 49
The Built-In Len Function It is appropriate here to also mention the built-in
function len, which is useful when you need to find the length (i.e., the number
ofelements)ofanarray.11
A quickdemonstrationofzerosandlenmaygo like this,
In [1]: from numpy import zeros
In [2]: x = zeros(3, int) # get array with integer zeros
In [3]: x
Out[3]: array([ 0, 0, 0])
In [4]: y = zeros(3) # get array with floating point zeros
In [5]: y
Out[5]: array([ 0., 0., 0.])
In [6]: y[0] = 0.0; y[1] = 1.0; y[2] = 2.0 # overwrite
In [7]: y
Out[7]: array([ 0., 1., 2.])
In [8]: len(y)
Out[8]: 3
Note that the linex = zeros(3, int)could,alternatively,havebeenwrittenabit
more informativeasx = zeros(3, dtype=int),wheredtypemeans data type.
Just like with linspace, the line y = zeros(3) instructs Python to reserve, or
allocate, space in memory for the array produced by zeros. As we see from the
dialogue, thearraygets the nameyand will have three elements, all with a floating
pointzerovalue.Eachelement iny isnextoverwrittenby“thenumbersweactually
wanted”. Strictly speaking, the assignmenty[0] = 0.0was redundanthere, since
thevalueofy[0]wasknowntobe0.0frombefore.It shouldbementioned, though,
thatprogrammersdeliberatelywritesuchseeminglyredundantstatementsfromtime
to time,meaning to tell a humancode interpreter that thevalue isnot“accidental”.
In our dialogue here, one explicit statement was written for each element value
we changed, i.e. as y[0] = 0.0; y[1] = 1.0; y[2] = 2.0. For arrays with
just a few elements, this is acceptable. However, with many elements, this is
obviously not the way to go. Longer arrays are typically first generated byzeros
(or otherwise), before individual array elements get new values in some loop
arrangement(explainedin Chap.3).
The Array Function Another handy way of creating an array, is by using the
functionarray, e.g., like this,
In [1]: from numpy import array
In [2]: x = array([0, 1, 2]) # get array with integers
In [3]: x
Out[3]: array([0, 1, 2])
In [4]: x = array([0., 1., 2.]) # get array with real numbers
11 Thelen function may also be used withother objects, e.g., lists (Sect.5.1).
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