1.5 A Python Program with Vectorization and Plotting
19
Here, pyplot is a module in the matplotlib package 15 that is named plt when
imported. Thus, when imported this way, all items from pyplot must have the prefix
plt. We will stick to this import and naming standard for pyplot also in the present
book, whenever plotting is on the agenda.
1.4.5 The Modules/Packages Used in This Book
Some readers might be curious to know which libraries are used in this book (apart
from the modules we make ourselves). Well, here they are:
• math—see, e.g., ball_angle.py, Sect. 1.3.
• numpy—see, e.g., check_functions.py above.
• matplotlib.pyplot—see, e.g., ball_plot.py, Sect. 1.5.
• random—see, e.g., throw_2_dice.py in Sect. 2.4.
• sympy—see, e.g., Sect. 5.3.
• timeit—see, e.g., Sect. 5.6.
• sys—see, e.g., Sect. 7.2.2.
These libraries are all well known to Python programmers. The three first ones
(math, numpy and matplotlib.pyplot) are used repeatedly throughout the
text, while the remaining ones (random, sympy, timeit and sys) appear just
occasionally.
Not listed, are two modules that are used just once each, the keyword module
(Sect. 2.2) and the os module (Sect. 9.2.4). It should be mentioned that we also use
a package called odespy (Sect. 8.4.6), previously developed by one of the authors
(Langtangen).
1.5 A Python Program with Vectorization and Plotting
We return to the problem where a ball is thrown up in the air and we have a formula
for the vertical position y of the ball. Say we are interested in y at every milli-second
for the first second of the flight. This requires repeating the calculation of y =
v 0 t − 0.5gt 2 one thousand times. As we will see, the computed heights appear very
informative when presented graphically with time, as opposed to a long printout of
all the numbers.
The Program In Python, the calculations and the visualization of the curve may
be done with the program ball_plot.py, reading
import numpy as np
import matplotlib.pyplot as plt
v0 = 5
g = 9.81
15 The matplotlib package (https://matplotlib.org/) comes with Anaconda. If you have not
installed Anaconda, you may have to install matplotlib separately.
Précédent

- 41/350

Suivant