Seite - 63 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 63 -
Text der Seite - 63 -
3.2 TheCompositeTrapezoidalRule 63
3.2.4 AlternativeFlatSpecial-PurposeImplementation
Let us illustrate the implementation implied by alternative 1 in theProgrammer’s
dilemma box in Sect. 3.2.2. That is, wemake a special-purpose codewhere we
adapt thegeneral formula (3.17) to the specificproblem R1
0 3t2et 3
dt.
Basically,we use afor loop to compute the sum. Each termwithf.x/ in the
formula (3.17) is replaced by 3t2et 3
,x by t, andh by t 1. Afirst try atwriting
aplain,flat programdoing thespecial calculation is
from math import exp
a = 0.0; b = 1.0
n = input(’n: ’)
dt = float(b - a)/n
# Integral by the trapezoidal method
numerical = 0.5*3*(a**2)*exp(a**3) + 0.5*3*(b**2)*exp(b**3)
for i in range(1, n):
numerical += 3*((a + i*dt)**2)*exp((a + i*dt)**3)
numerical *= dt
exact_value = exp(1**3) - exp(0**3)
error = abs(exact_value - numerical)
rel_error = (error/exact_value)*100
print ’n=%d: %.16f, error: %g’ % (n, numerical, error)
Theproblemwith theabovecode is at least three-fold:
1. Weneed to reformulate (3.17) forourspecialproblemwithadifferentnotation.
2. The integrand3t2et 3
is insertedmany times in thecode,whichquickly leads to
errors.
3. A lot of edits are necessary to use the code to compute a different integral –
theseedits are likely to introduceerrors.
The potential errors involved in point 2 serve to illustrate how important it is to
use Python functions asmathematical functions. Herewe have chosen to use the
lambdafunction todefine the integrandas thevariablev:
from math import exp
v = lambda t: 3*(t**2)*exp(t**3) # Function to be integrated
a = 0.0; b = 1.0
n = input(’n: ’)
dt = float(b - a)/n
1Replacing h by t is not strictly required asmany use h as interval also along the time axis.
Nevertheless, t is an even more popular notation for a small time interval, so we adopt that
commonnotation.
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