Page - 67 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 67 -
Text of the Page - 67 -
3.3 TheCompositeMidpointMethod 67
3.3.2 Implementation
We follow the advice and lessons learned from the implementation of the trape-
zoidalmethodandmakea functionmidpoint(f, a, b, n) (inafilemidpoint.
py) for implementing thegeneral formula (3.21):
def midpoint(f, a, b, n):
h = float(b-a)/n
result = 0
for i in range(n):
result += f((a + h/2.0) + i*h)
result *= h
return result
Wecan test the functionasweexplained for the similartrapezoidalmethod.
Theerror inourparticularproblem R1
0 3t2et 3
dtwithfour intervals isnowabout0.1
in contrast to 0.2 for the trapezoidal rule. This is in fact not accidental: one can
showmathematically that theerrorof themidpointmethod is abit smaller than for
the trapezoidalmethod. The differences are seldom of any practical importance,
andonalaptopwecaneasilyusenD106andget theanswerwithanerrorofabout
10 12 in acoupleof seconds.
3.3.3 ComparingtheTrapezoidalandtheMidpointMethods
The next example shows how easy we can combine the trapezoidal and
midpointfunctionstomakeacomparisonof the twomethodsin thefilecompare_
integration_methods.py:
from trapezoidal import trapezoidal
from midpoint import midpoint
from math import exp
g = lambda y: exp(-y**2)
a = 0
b = 2
print ’ n midpoint trapezoidal’
for i in range(1, 21):
n = 2**i
m = midpoint(g, a, b, n)
t = trapezoidal(g, a, b, n)
print ’%7d %.16f %.16f’ % (n, m, t)
Note theeffortsput intonice formatting– theoutputbecomes
n midpoint trapezoidal
2 0.8842000076332692 0.8770372606158094
4 0.8827889485397279 0.8806186341245393
8 0.8822686991994210 0.8817037913321336
16 0.8821288703366458 0.8819862452657772
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