Page - 73 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 73 -
Text of the Page - 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
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