Seite - 39 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 39 -
Text der Seite - 39 -
2.3 ForLoops 39
will contain the largest number from the arrayy. Whenyou run the program, you
get
The largest height achieved was 1.274210 m
whichcompares favorably to theplot thatpopsup.
To implement the traversingofarrayswith loopsandindices, is sometimeschal-
lenging toget right. Youneed tounderstand the start, stop and step length choices
foranindex,andalsohowtheindexshouldenterexpressionsinsidethe loop.At the
same time, however, it is something that programmers dooften, so it is important
todevelop the right skills on thesematters.
Havingoneloopinsideanother,referredtoasadoubleloop, issometimesuseful,
e.g., when doing linear algebra. Say we want to find the maximum among the
numbersstored ina4 4matrixA.Thecode fragmentcould look like
largest_number = A[0][0]
for i in range(4):
for j in range(4):
if A[i][j] > largest_number:
largest_number = A[i][j]
Here, all thej indices (0 - 3)will be covered for eachvalue of indexi. First, i
staysfixedati = 0,whilej runsoverall its indices. Then,i staysfixedati = 1
whilej runsover all its indices again, and soon. SketchAonapieceofpaper and
follow the first few loop iterations by hand, then youwill realize how the double
loopconstructionworks.Using two loops is just a special caseofusingmultipleor
nested loops, andutilizingmore than two loops is just a straightforward extension
ofwhatwasshownhere.Note,however, that the loopindexname inmultiple loops
must be unique to each of the nested loops. Note also that each nested loopmay
haveasmanycode linesasdesired,bothbeforeandafter thenext inner loop.
Thevectorizedcomputationofheights thatwedid inball_plot.py(Sect.1.4)
could alternatively havebeendoneby traversing the timearray (t) and, for eacht
element, computingtheheightaccording to the formulayDv0t 12gt2. However,
it is important to know that vectorization goesmuch quicker. So when speed is
important,vectorization isvaluable.
Useloopstocomputesums
One important useof loops, is to calculate sums. Asa simple example, assume
somevariablexgivenby themathematical expression
xD NX
iD1 2 i;
i.e., summing up theN first even numbers. For somegivenN , sayN D 5,x
would typicallybecomputed inacomputerprogramas:
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik