Seite - 71 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 71 -
Text der Seite - 71 -
3.3 Branching(if,elifandelse) 71
The solution illustrates a simple, and very common, search procedure, looping
through an array by use of a for loop to find the maximum value. Our program
ball_max_height.pyreads
import numpy as np
import matplotlib.pyplot as plt
v0 = 5 # Initial velocity
g = 9.81 # Acceleration of gravity
t = np.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,
# and we need to find the largest value within y.
largest_height = y[0] # Starting value for search
for i in range(1, len(y), 1):
if y[i] > largest_height:
largest_height = y[i]
print(’The largest height achieved was {:g} m’.format(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()
We focus our attention on the new thing here, the search performed by thefor
loop.The value iny[0] is used as a starting value forlargest_height. The very
first check then, tests whethery[1] is larger than this height. If so,y[1] is stored
as the largest height. The for loop then updates i to 2, and continues to check
y[2], and so on. Each time we find a larger number, we store it. When finished,
largest_heightwill contain the largestnumber fromthearrayy.
Whenyourun theprogram,youget
The largest height achieved was 1.27421 m
whichcompares favorably to theplot that popsup (seeFig.1.1).
The observant reader has already seen the similarity of finding the maximum
height and finding the time of flight, as we addressed previously in Sect.3.2.1.
In fact, we could alternatively have solved the maximum height problem here by
utilizing that y[i+1] > y[i] as the ball moves towards the top. Doing this, our
search loopcouldhavebeenwritten
i = 0
while y[i+1] > y[i]:
i = i + 1
When the conditiony[i+1] > y[i]becomesFalse, we could reporty[i+1] as
ourapproximationof themaximumheight, forexample.
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