Page - 38 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 38 -
Text of the Page - 38 -
38 2 BasicConstructions
1 is thenused (combinedwith the startingat 0). Thus, callingrange, for example,
as
range(6)
would return the integers0, 1, 2, 3, 4, 5.
Note that decreasing integersmaybeproducedby lettingstart > stop com-
bined with a negative step. This makes it easy to, e.g., traverse arrays in either
direction.
Let usmodifyball_plot.py fromSect. 1.4 to illustrate howusefulfor loops
are if you need to traverse arrays. In that examplewe computed the height of the
ball at everymilli-second during thefirst secondof its (vertical) flight andplotted
theheightversus time.
Assumewewant tofind themaximumheight during that time, howcanwedo
itwith a computer program? One alternativemay be to compute all the thousand
heights, store theminanarray,and then run through thearray topickout themaxi-
mum.Theprogram,namedball_max_height.py,may lookas follows.
import matplotlib.pyplot as plt
v0 = 5 # Initial velocity
g = 9.81 # Acceleration of gravity
t = linspace(0, 1, 1000) # 1000 points in time interval
y = v0*t - 0.5*g*t**2 # Generate all heights
# At this point, the array y with all the heights is ready.
# Now we need to find the largest value within y.
largest_height = y[0] # Starting value for search
for i in range(1, 1000):
if y[i] > largest_height:
largest_height = y[i]
print "The largest height achieved was %f m" % (largest_height)
# We might also like to plot the path again just to compare
plt.plot(t,y)
plt.xlabel(βTime (s)β)
plt.ylabel(βHeight (m)β)
plt.show()
There is nothingnewhere, except thefor loopconstruction, so let us lookat it
inmoredetail. As explainedabove, Pythonunderstands that afor loop is desired
when it sees thewordfor. Therange() functionwill produce integers from,and
including, 1, up to, and including, 999, i.e. 1000 1. The value in y[0] is used
as the preliminary largest height, so that, e.g., the very first check that ismade is
testingwhethery[1] is larger than this height. If so,y[1] is stored as the largest
height. The for loop thenupdatesi to 2, and continues to checky[2], and so on.
Each timewefinda larger number,we store it. Whenfinished,largest_height
back to the
book Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik