Page - 146 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 146 -
Text of the Page - 146 -
146 6 ComputingIntegralsandTestingCode
Remark
The trapezoidal and midpoint methods are just two examples in a jungle of
numerical integration rules. Other famous methods are Simpsonβs rule and
Gaussquadrature.Theyall work in the sameway:
β« b
a f(x)dxβ nβ1β
i=0 wif(xi).
That is, the integral is approximatedby a sum of functionevaluations,where
each evaluationf(xi) is given a weight wi. The different methods differ in
the way they construct the evaluation points xi and the weights wi. Higher
accuracycanbeobtainedbyoptimizing the locationofxi.
6.4 VectorizingtheFunctions
Thefunctionsmidpointandtrapezoidalusuallyrunfast inPythonandcompute
an integral to satisfactory precision within a fraction of a second. However, long
loops in Pythonmay runslowly in more complicated implementations.To increase
speed, the loopscanbereplacedbyvectorizedcode.The integrationfunctionsoffer
simpleandgoodexamplesonhowtovectorize loops.
We have already seen simple examples on vectorization in Sect.1.5, when we
evaluateda mathematical functionf(x) fora largenumberofx values stored in an
array.Basically,we canwrite
def f(x):
return exp(-x)*sin(x) + 5*x
from numpy import exp, sin, linspace
x = linspace(0, 4, 101) # coordinates from 100 intervals on [0, 4]
y = f(x) # all points evaluated at once
The resulty is an array that, alternatively, could have been computed by runninga
for loopover the individualxvaluesandcalledf for eachvalue.Vectorizationes-
sentiallyeliminates thisexplicit loopinPython(i.e., the loopingoverxandapplica-
tionoff toeachxvalueareinsteadperformedinalibrarywithfast,compiledcode).
6.4.1 VectorizingtheMidpointRule
We start by vectorizing themidpoint function, sincetrapezoidal is not equally
straightforwardtovectorize.Inbothcases,ourvectorizationwill removetheexplicit
loop.The fundamental ideasof thevectorizedalgorithmare to
1. computeandstoreall theevaluationpoints in onearrayx
2. callf(x) toproduceanarrayofcorrespondingfunctionvalues
3. use thesum function to sumup thef(x)values
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik