Page - 170 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 170 -
Text of the Page - 170 -
170 6 ComputingIntegralsandTestingCode
Fig. 6.4 Illustration of the rectangle method withevaluating the rectangle height byeither the left
or right point
Exercise6.7:WriteTest Functions for β«4
0 β
xdx
We want to test how the trapezoidal function works for the integral β«4
0 β
xdx.
Two of the tests in test_trapezoidal.py are meaningful for this integral.
Compute by hand the result of using two or three trapezoids and modify the
test_trapezoidal_one_exact_result function accordingly. Then modify
test_trapezoidal_conv_rate tohandle thesquare root integral.
Filename:test_trapezoidal3.py.
Remarks The convergence rate test fails. Printing out r shows that the actual
convergencerate for this integral is1.5andnot2.Thereason is that theerror in the
trapezoidal method6 is β(bβa)3nβ2f β²β²(ΞΎ) for some (unknown) ΞΎ β [a,b]. With
f(x)=βx,f β²β²(ΞΎ)βββasΞΎ β0,pointingtoapotentialproblemin thesizeof
theerror.Runninga testwitha>0, say β«4
0.1 β
xdx showsthat theconvergencerate
is indeedrestored to2.
Exercise6.8:RectangleMethods
Themidpointmethoddividestheintervalofintegrationintoequal-sizedsubintervals
andapproximatestheintegralineachsubintervalbyarectanglewhoseheightequals
the function value at the midpoint of the subinterval. Instead, one might use either
the left or right end of the subinterval as illustrated in Fig.6.4. This defines a
rectangle method of integration. The height of the rectangle can be based on the
leftor rightendor themidpoint.
a) Write a functionrectangle(f, a, b, n, height=βleftβ) for computing
an integral β«b
a f(x)dx by the rectangle method with height computed based on
thevalueofheight,which is eitherleft,right, ormid.
b) Write three test functions for the three unit test procedures described in
Sect.6.6.2. Make sure you test for height equal to left, right, and mid.
Youmaycall themidpoint functionforcheckingtheresultwhenheight=mid.
6 http://en.wikipedia.org/wiki/Trapezoidal_rule#Error_analysis.
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