None
Here are essential things you need to know about Python functions:
def
or lambda
statements.def
defines multiline functions that terminate and return values specified by the return
statement.lambda
defines single line functions that return a value.The following cells demonstrate these points in the process of computing a numerical solution to the system of differential equations describing the motion of a mass $m$ subject to a time-varying force $f(t)$
\begin{align} \frac{dx}{dt} & = v \\ \frac{dv}{dt} & = \frac{1}{m} f(t) \\ \end{align}for various choices of $f(t)$. The cells show several different ways of coding $f(t)$, and the vector valued right hand sides of this system of differential equations, as Python functions.
The first aspect of this simulation is to establish a specific function to describe the time-varying force $f(t)$. As an example, the following cell creates a plot of $\cos(t)$ using the numpy
library.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 20, 1000)
plt.plot(t, np.cos(t))
[<matplotlib.lines.Line2D at 0x11a88ef10>]
In Python, the notation np.cos(t)
returns the value of $cos(t)$ for a specific value of time $t$. The notation np.cos
(note the absence of parentheses after the function name) refers to the function itself, the function being the object that does the computation. An important feature of Python is that functions can be assigned and manipulated like other Python objects.
The following cell shows how the function np.cos
can be assigned to a Python symbol f
and then used in subsequent calculations.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
f = np.cos
t = np.linspace(0, 20, 1000)
plt.plot(t, f(t))
[<matplotlib.lines.Line2D at 0x11a987490>]
Notice that f
and f(t)
are different things. By itself, the symbol f
refers to the function. With a following parentheses and any required arguments, f(t)
returns whatever was listed after the return
statement inside of the function. If these is no return
statement of if there is nothing listed then the function returns None
.
print("f = ", f)
print("f(0) = ", f(0))
f = <ufunc 'cos'> f(0) = 1.0
lambda
¶There are many situations where all you need is a simple function to encapsulate a calculation that can be done in one line of Python code. Python's lambda
statement is ideal for this purpose. Learning to use the lambda
function well allows you to write more compact and readable code.
The following cell uses lambda
to create a function f(t)
with a single argument t
that returns the exponentially damped sinusoid $e^{-t/4} sin(t)$.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
f = lambda t: np.exp(-t/4) * np.sin(t)
t = np.linspace(0, 20, 1000)
plt.plot(t, f(t))
[<matplotlib.lines.Line2D at 0x11aa66b50>]
It's hard to overstate the utility of lambda
functions when combined with other features of Python. For example, while lambda
functions are limited to one line statements, when combined with Python's conditional expression your code can incorporate logical conditions.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
f = np.vectorize(lambda t: np.exp(-t/4) * np.sin(t) if t >= 0 else 0.0)
t = np.linspace(-5, 20, 1000)
plt.plot(t, f(t))
[<matplotlib.lines.Line2D at 0x119f864d0>]
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
f = np.vectorize(lambda t: 0.0 if t < 0 else 1.0 if t < 2 else -1.0 if t < 4 else 0.0)
t = np.linspace(-5, 20, 1000)
plt.plot(t, f(t))
[<matplotlib.lines.Line2D at 0x11aad7510>]
def
¶Python provides two methods of creating functions. The most general method is the def
statement that defines the name and arguments of a function, followed by accompanying return
statement to specifies what the function returns.
As an example, the following code creates a function that takes a value time ($t$), position ($x$), and velocity ($v$), and returns the a two element array corresponding to the right hand side of the differential equations
import numpy as np
def deriv(t, *args):
x = args[0]
v = args[1]
return np.array([v, f(t)])
u = np.cos
deriv(0, 0, 0)
array([0., 1.])
CBE30338.plotter()
¶CBE30338.plotter()
is a function that simplifies creation of figures with the mulitple plotting axes.
%reload_ext autoreload
%matplotlib inline
import numpy as np
import CBE30338
t = np.linspace(0, 20)
s = np.sin(t)
c = np.cos(t)
sin, cos = CBE30338.plotter('Sine', 'Cosine')
sin.plot(t, s)
cos.plot(t, c)
[<matplotlib.lines.Line2D at 0x11cef1b90>]