Seite - 90 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 90 -
Text der Seite - 90 -
90 3 Computing Integrals
a) Write a functionrectangle(f, a, b, n, height=’left’) for computing
an integral Rb
a f.x/dx by the rectanglemethodwithheight computedbasedon
thevalueofheight,which is eitherleft,right,ormid.
b) Write three test functions for the three unit test procedures described in
Sect.3.4.2.Makesureyoutest forheightequal toleft,right, andmid.You
maycall themidpoint functionforchecking the resultwhenheight=mid.
Hint Edittest_trapezoidal.py.
Filename:rectangle_methods.py.
Exercise3.9:Adaptive integration
Supposewewant touse the trapezoidalormidpointmethod tocomputean
integralRb
a f.x/dxwithanerror less thanaprescribed tolerance .What is theappropriate
sizeofn?
Toanswer thisquestion,wemayenteran iterativeprocedurewherewecompare
the results producedbyn and2n intervals, and if the difference is smaller than ,
the value corresponding to 2n is returned. Otherwise, we halven and repeat the
procedure.
Hint Itmaybeagood idea to organizeyourcode so that the functionadaptive_
integrationcanbeusedeasily in futureprogramsyouwrite.
a) Write a function
adaptive_integration(f, a, b, eps, method=midpoint)
that implements the ideaabove(epscorrespondsto the tolerance , andmethod
canbemidpointortrapezoidal).
b) Test themethod on R2
0 x2dx and R2
0 p
xdx for D 10 1;10 10 andwrite out
theexacterror.
c) Makeaplot ofnversus 2 Œ10 1;10 10 forR2
0 p
xdx. Use logarithmic scale
for .
Filename:adaptive_integration.py.
Remarks The typeofmethodexplored in this exercise is calledadaptive, because
it tries toadapt thevalueofn tomeetagivenerrorcriterion. Thetrueerrorcanvery
seldombecomputed (sincewedonotknowtheexact answer to the computational
problem),soonehas tofindother indicatorsof theerror,suchas theoneherewhere
the changes in the integral value, as thenumberof intervals is doubled, is taken to
reflect theerror.
Exercise3.10: Integratingxraised tox
Consider the integral
I D 4Z
0 xxdx:
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