Seite - 72 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 72 -
Text der Seite - 72 -
72 3 Computing Integrals
Ifwecannotmake tests like0.1 + 0.2 == 0.3,whatshouldwe thendo?The
answer is thatwemust accept some small inaccuracyandmakea testwith a toler-
ance. Here is the recipe:
>>> a = 0.1; b = 0.2; expected = 0.3
>>> computed = a + b
>>> diff = abs(expected - computed)
>>> tol = 1E-15
>>> diff < tol
True
Herewe have set the tolerance for comparison to10 15, but calculating0.3 -
(0.1 + 0.2) shows that it equals-5.55e-17, soa lower tolerancecouldbeused
in this particular example. However, inother calculationswehave little ideaabout
howaccurate theanswer is (therecouldbeaccumulationofroundingerrors inmore
complicated algorithms), so 10 15 or 10 14 are robust values. Aswedemonstrate
below,these tolerancesdependonthemagnitudeof thenumbersin thecalculations.
Doing an experiment with 10k C0:3 .10k C0:1C0:2/ for k D 1;:: :;10
shows that the answer (which should be zero) is around 1016 k. Thismeans that
the tolerancemust be larger ifwe computewith larger numbers. Setting a proper
tolerance therefore requires some experiments to see what level of accuracy one
canexpect. Awayoutof thisdifficulty is toworkwith relative insteadofabsolute
differences. Ina relativedifferencewedividebyoneof theoperands, e.g.,
aD10k C0:3; bD .10k C0:1C0:2/; cD a b
a :
Computing this c for variousk shows a value around10 16. A safer procedure is
thus touse relative differences.
3.4.4 ConstructingUnitTestsandWritingTestFunctions
Pythonhasseveralframeworksforautomaticallyrunningandcheckingapotentially
very largenumber of tests for parts of your software byone command. This is an
extremely useful feature during program development: whenever you have done
somechanges tooneormorefiles, launchthe test commandandmakesurenothing
isbrokenbecauseofyouredits.
The test frameworks nose and py.test are particularly attractive as they are
veryeasy touse. Tests are placed in special test functions that the frameworkscan
recognizeandrun foryou.The requirements toa test functionaresimple:
thenamemust startwithtest_
the test functioncannothaveanyarguments
the tests inside test functionsmustbebooleanexpressions
a boolean expression bmust be testedwith assert b, msg, where msg is an
optionalobject (stringornumber) tobewrittenoutwhenb is false
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