Seite - 62 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 62 -
Text der Seite - 62 -
62 3 Computing Integrals
we just put the statementsweotherwisewouldhaveput in amainprogram, inside
a function:
def application():
from math import exp
v = lambda t: 3*(t**2)*exp(t**3)
n = input(’n: ’)
numerical = trapezoidal(v, 0, 1, n)
# Compare with exact result
V = lambda t: exp(t**3)
exact = V(1) - V(0)
error = exact - numerical
print ’n=%d: %.16f, error: %g’ % (n, numerical, error)
Nowwecomputeourspecialproblembycallingapplication()as theonlystate-
ment in themain program. Both the trapezoidal and application functions
reside in thefiletrapezoidal.py,whichcanbe runas
Terminal
Terminal> python trapezoidal.py
n: 4
n=4: 1.9227167504675762, error: -0.204435
3.2.3 MakingaModule
Whenwe have the different pieces of our programas a collection of functions, it
is very straightforward to create amodule that can be imported in other programs.
That is, having our code as amodule,means that thetrapezoidal function can
easily be reused by other programs to solve other problems. The requirements of
amodule are simple: put everything inside functions and let function calls in the
mainprogrambe in theso-called test block:
if __name__ == ’__main__’:
application()
The if test is true if the module file, trapezoidal.py, is run as a program
and false if themodule is imported in another program. Consequently, whenwe
do from trapezoidal import trapezoidal in some file, the test fails and
application() is not called, i.e., our special problem is not solved andwill not
print anythingon the screen. On theotherhand, ifwe runtrapezoidal.py in the
terminalwindow, the test condition is positive,application() is called, andwe
getoutput in thewindow:
Terminal
Terminal> python trapezoidal.py
n: 400
n=400: 1.7183030649495579, error: -2.12365e-05
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