Seite - 156 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 156 -
Text der Seite - 156 -
156 6 ComputingIntegralsandTestingCode
error problems explained in Sect.6.6.3, and we must use a test with tolerance
instead:
def test_add():
expected = 0.3
computed = add(0.1, 0.2)
tol = 1E-14
diff = abs(expected - computed)
assert diff < tol, ’diff={:g}’.format(diff)
Below we shall write test functions for each of the three test procedures we
suggested: comparison with hand calculations, checking problems that can be
exactly solved, and checking convergencerates. We stick to testing the trapezoidal
integration code and collect all test functions in one common file by the name
test_trapezoidal.py.
Hand-Computed Numerical Results Our previous hand calculations for two
trapezoidscanbe utilized in a test function like this:
from trapezoidal import trapezoidal
def test_trapezoidal_one_exact_result():
"""Compare one hand-computed result."""
from math import exp
v = lambda t: 3*(t**2)*exp(t**3)
n = 2
computed = trapezoidal(v, 0, 1, n)
expected = 2.463642041244344
error = abs(expected - computed)
tol = 1E-14
success = error < tol
msg = ’error={:g} > tol={:g}’.format(error, tol)
assert success, msg
Note the importanceofcheckingcomputedagainstexpectedwith a tolerance:
roundingerrors from the arithmetics insidetrapezoidalwill not make the result
exactly like thehand-computedone.
SolvingaProblemWithoutNumericalErrors Weknowthat the trapezoidalrule
isexactfor linear integrands.Choosingtheintegral ∫4.4
1.2 (6x−4)dxasatestcase, the
correspondingtest functioncould, forexample,checkwith threedifferentnvalues,
andmay look like
def test_trapezoidal_linear():
"""Check that linear functions are integrated exactly."""
f = lambda x: 6*x - 4
F = lambda x: 3*x**2 - 4*x # Anti-derivative
a = 1.2; b = 4.4
expected = F(b) - F(a)
tol = 1E-14
for n in 2, 20, 21:
computed = trapezoidal(f, a, b, n)
error = abs(expected - computed)
success = error < tol
msg = ’n={:d}, err={:g}’.format(n, error)
assert success, msg
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