Seite - 9 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 9 -
Text der Seite - 9 -
1.4 APythonProgramwithVectorizationandPlotting 9
We will often use this import statement and then get access to all common
mathematical functions. This latter statement is inserted in a program named
ball_angle.py:
from math import *
x = 10 # Horizontal position
y = 10 # Vertical position
angle = atan(y/x)
print (angle/pi)*180
Thisprogramrunsperfectly andproduces45.0asoutput, as it should.
At first, it may seem cumbersome to have code in libraries, since you have to
knowwhich library to import to get the desired functionality. Having everything
available anytime would be convenient, but this also means that you fill up the
memory of your programwith a lot of information that you ratherwould use for
computationsonbigdata. Pythonhassomany librarieswith somuchfunctionality
thatonesimplyneeds to importwhat is needed ina specificprogram.
1.4 APythonProgramwithVectorizationandPlotting
Wereturn to theproblemwhereaball is thrownupin theairandwehaveaformula
for the vertical position y of the ball. Saywe are interested in y at everymilli-
second for the first secondof the flight. This requires repeating the calculation of
yDv0t 0:5gt2one thousand times.
Wewill also drawagraphofy versus t for t 2 Œ0;1 . Drawing suchgraphson
a computer essentiallymeans drawing straight lines between points on the curve,
soweneedmanypoints tomake thevisual impressionofasmoothcurve.Withone
thousandpoints, asweaimtocomputehere, thecurve looks indeedverysmooth.
InPython, the calculations and thevisualizationof the curvemaybedonewith
theprogramball_plot.py, reading
from numpy import linspace
import matplotlib.pyplot as plt
v0 = 5
g = 9.81
t = linspace(0, 1, 1001)
y = v0*t - 0.5*g*t**2
plt.plot(t, y)
plt.xlabel(’t (s)’)
plt.ylabel(’y (m)’)
plt.show()
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