Page - 10 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 10 -
Text of the Page - 10 -
10 1 TheFirstFewSteps
This programproduces a plot of the vertical positionwith time, as seen inFig-
ure 1.1. As you notice, the code lines from theball.pyprogram inChapter 1.2
havenotchangedmuch,but theheight is nowcomputedandplotted fora thousand
points in time!
Let us takea lookat thedifferencesbetween thenewprogramandourprevious
program.Fromthe top, thefirstdifferencewenoticeare the lines
from numpy import *
from matplotlib.pyplot import *
Yousee thewordimporthere, soyouunderstand thatnumpymustbea library, or
moduleinPythonterminology.This librarycontainsa lotofveryuseful functional-
ity formathematical computing,while thematplotlib.pyplotmodule contains
functionality for plotting curves. The above import statement constitutes a quick
wayof populatingyourprogramwith all necessary functionality formathematical
computing and plotting. However, we actuallymake use of only a few functions
in the present program: linspace,plot, xlabel, and ylabel. Many computer
scientists will therefore argue that we should explicitly import whatwe need and
noteverything(the star*):
from numpy import linspace
from matplotlib.pyplot import plot, xlabel, ylabel
Otherswill claim that we should do a slightly different import and prefix library
functionsby the libraryname:
import numpy as np
import matplotlib.pyplot as plt
...
t = np.linspace(0, 1, 1001)
...
plt.plot(t, y)
plt.xlabel(βt (s)β)
plt.ylabel(βy (m)β)
Wewilluseall three techniques,andsinceallof themare insowidespreaduse,you
shouldbe familiarwith them too. However, for themost part in this bookweshall
do
from numpy import *
from matplotlib.pyplot import *
for convenience and for making Python programs that look very similar to their
Matlabcounterparts.
The functionlinspace takes3parameters, and isgenerallycalledas
linspace(start, stop, n)
This is our first example of a Python function that takesmultiple arguments. The
linspace function generates n equally spaced coordinates, starting with start
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