Seite - 36 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 36 -
Text der Seite - 36 -
36 2 BasicConstructions
When run, this program first prints the sum of x and y (i.e., 5), and then it
prints theproduct (i.e., 6).Wesee thattreat_xy takes a functionnameas itsfirst
parameter. Insidetreat_xy, that function isused to actually call the function that
was given as input parameter. Therefore, as shown, wemay call treat_xywith
eithersum_xyorprod_xy,dependingonwhetherwewant thesumorproductofx
andy tobecalculated.
Functionsmayalsobedefinedwithinother functions. It that case, theybecome
local functions, or nested functions, knownonly to the function insidewhich they
aredefined. Functionsdefined inmainare referred toasglobal functions. Anested
functionhasfullaccess toallvariablesintheparentfunction, i.e. thefunctionwithin
which it is defined.
Short functions can be defined in a compact way, using what is known as
a lambdafunction:
f = lambda x, y: x + 2*y
# Equivalent
def f(x, y):
return x + 2*y
Thesyntaxconsists oflambda followedbya seriesof arguments, colon, andsome
Pythonexpression resulting in anobject to be returned fromthe function. Lambda
functionsareparticularlyconvenientas functionarguments:
print treat_xy(lambda x, y: x*y, x, y)
Overheadoffunctioncalls
Function calls have the downside of slowing down program execution. Usu-
ally, it is a good thing to split a program into functions, but in very computing
intensiveparts, e.g., inside longloops,onemustbalancetheconvenienceofcall-
ing a function and the computational efficiencyof avoiding function calls. It is
a good rule to develop a programusing plenty of functions and then in a later
optimization stage, when everything computes correctly, remove function calls
that arequantified to slowdownthecode.
Here isa littleexampleinIPythonwherewecalculate theCPUtimefordoing
arraycomputationswithandwithoutahelper function:
In [1]: import numpy as np
In [2]: a = np.zeros(1000000)
In [3]: def add(a, b):
...: return a + b
...:
In [4]: %timeit for i in range(len(a)): a[i] = add(i, i+1)
The slowest run took 16.01 times longer than the fastest.
This could mean that an intermediate result is being cached
1 loops, best of 3: 178 ms per loop
In [5]: %timeit for i in range(len(a)): a[i] = i + (i+1)
10 loops, best of 3: 109 ms per loop
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