Seite - 73 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 73 -
Text der Seite - 73 -
3.4 Testing 73
Supposewehavewrittena function
def add(a, b):
return a + b
Acorresponding test functioncan thenbe
def test_add()
expected = 1 + 1
computed = add(1, 1)
assert computed == expected, ’1+1=%g’ % computed
Test functions canbe in anyprogramfile or in separatefiles, typicallywith names
startingwithtest. You can also collect tests in subdirectories: runningpy.test
-s -vwill actually run all tests in all test*.pyfiles in all subdirectories, while
nosetests -s -v restricts the attention to subdirectorieswhosenames startwith
testorendwith_testor_tests.
As longasweadd integers, theequality test in thetest_add function is appro-
priate,but ifwetry tocalladd(0.1, 0.2) instead,wewill face theroundingerror
problemsexplained inSect. 3.4.3,andwemustusea testwith 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’ % diff
Belowwe shall write test functions for each of the three test procedures we
suggested: comparisonwith hand calculations, checking problems that can be ex-
actly solved, and checking convergence rates. We stick to testing the trapezoidal
integration code and collect all test functions in one common file by the name
test_trapezoidal.py.
Hand-computednumericalresults Ourprevioushandcalculationsfor twotrape-
zoids can be checked against thetrapezoidal function inside a test function (in
afiletest_trapezoidal.py):
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’ % (errror, tol)
assert success, msg
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