Seite - 139 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 139 -
Text der Seite - 139 -
6.2 TheCompositeTrapezoidalRule 139
function.Thus, in the presentcase, we put the statements (otherwiseplaced a main
program)insidea functionnamedapplication.
To achieve flexibility, we proceed to modifytrapezoidal.py, so that it has a
test blockand functiondefinitionsoftrapezoidalandapplication:
def trapezoidal(f, a, b, n):
h = (b-a)/n
f_sum = 0
for i in range(1, n, 1):
x = a + i*h
f_sum = f_sum + f(x)
return h*(0.5*f(a) + f_sum + 0.5*f(b))
def application():
from math import exp
v = lambda t: 3*(t**2)*exp(t**3)
n = int(input(’n: ’))
numerical = trapezoidal(v, 0, 1, n)
# Compare with exact result
V = lambda t: exp(t**3)
exact = V(1) - V(0)
error = abs(exact - numerical)
print(’n={:d}: {:.16f}, error: {:g}’.format(n, numerical, error))
if __name__ == ’__main__’:
application()
With our newly gained knowledge about the making of modules, we understand
that theif test becomes true when the module file,trapezoidal.py, is run as a
program,and false when the module (or part of it) is imported in anotherprogram.
Consequently, with an import like from trapezoidal import trapezoidal,
the test fails and application() is not called. On the other hand, if we run
trapezoidal.pyas a program, the test condition is positiveandapplication()
is called. A call toapplication implies that our special problem gets computed.
The main program now gets very small, being just a single function call to
application.
Running theprogram,e.g.,withn=4gives theoutput
n=4: 1.9227167504675762, error: 0.204435
Clearly, with a module like the one shown here, thetrapezoidal function alone
(i.e., withoutapplication)can easily be importedby other programs to compute
other integrals.
6.2.3 ASpecificImplementation:What’stheProblem?
Let us illustrate the implementation implied by alternative 1 in the Programmer’s
dilemma box in Sect.6.2.2. That is, we make a special-purpose code, where we
adapt the general formula (6.17) to the specific problem ∫1
0 3t 2et 3
dt, in which the
integrandis avelocity functionv(t).
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik