A4 · Lesson 9 · More about functions
Small tools that fit together
Lesson 1's functions took a few numbers and returned one. Real engineering code leans on more: arguments that have sensible defaults, functions that hand back several results at once, and functions passed to other functions, like a root finder that works on whatever equation you give it. These features are what let a library of small, tested pieces turn into a design tool.
Predict
What does this print?
def gain(vout, vin=1.0):
return vout / vin
print(gain(5), gain(5, 2)) 5.0 2.5. vin=1.0 gives the argument a default, used when the caller leaves it out. gain(5) is 5 / 1.0 and gain(5, 2) is 5 / 2.
Name it
Arguments
def rc_corner(R, C, unit="Hz"):
w = 1 / (R * C)
if unit == "rad/s":
return w
return w / (2 * 3.141592653589793)
- Defaults:
unit="Hz"is used unless the caller passes something else. Parameters with defaults come after those without. - Keyword arguments:
rc_corner(1e3, 1e-6, unit="rad/s")names the argument, which reads clearly and can't be mixed up by position.
Returning several values
A function returns one object, but that object can be a tuple of values, and the caller can unpack it:
import math
def polar(x, y):
return math.hypot(x, y), math.degrees(math.atan2(y, x))
r, theta = polar(-3, 4) # 5.0, 126.87
Scope
Variables made inside a function are local: they exist only while it runs and don't touch variables of the same name outside. A function should get what it needs through its arguments and give results back with return. That's what makes it testable on its own.
Functions as values
A function is a value like any other, so you can pass it to another function. That's how general tools are written:
def average(f, a, b, n=1000):
"""The average of f over [a, b], sampled at n midpoints."""
h = (b - a) / n
total = 0.0
for k in range(n):
total += f(a + (k + 0.5) * h)
return total / n
import math
average(lambda t: math.sin(t)**2, 0, 2 * math.pi) # 0.5
lambda t: ... writes a small function inline, handy for passing a formula. Root finders (lesson 37), integrators (lesson 39) and ODE solvers (lessons 41 and 42) all take the function they work on as an argument.
Docstrings
A string just after def is the function's docstring: what it does, its arguments and units. help(rc_corner) prints it. Write one for anything you'll reuse.
Worked example
Write a function that returns both the current and the power for a resistor, and use it.
Show the solution
- Return both results as a tuple. Then unpack them at the call.
def resistor(V, R):
"""Current in A and power in W for V volts across R ohms."""
I = V / R
return I, V * I
I, P = resistor(12, 470)
print(f"{I*1e3:.3g} mA, {P:.3g} W") # 25.5 mA, 0.306 W
- Why a tuple. Returning a tuple keeps related results together, and unpacking names them at the call.
Answer for 12 V across 470 Ω the function returns 25.5 mA and 0.306 W.
Worked example
Find the RMS of a sine wave numerically.
Show the solution
- Write RMS as an average. RMS is the square root of the average of the square, so use the
averagefunction above.
import math
rms = math.sqrt(average(lambda t: math.sin(t)**2, 0, 2 * math.pi))
print(rms) # 0.7071067811865475
- Check. That's , as A5 will derive.
- Reuse it. The same three lines work for any waveform you can write as a function.
Answer the RMS of a unit sine wave is 0.7071, which is .
Check
Write divider(Vs, R1, R2=10e3) returning the output voltage, with R2 defaulting to 10 kΩ. Then set a = divider(Vs, R1) and b = divider(Vs, R1, R2=R1), with Vs = 5 and R1 = 1500.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write polar(x, y) returning the pair (r, theta) with theta in degrees from math.atan2. Then set r, theta = polar(x, y) for x = 5 and y = 4.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write average(f, a, b, n=1000) that averages f over n equally spaced midpoints of [a, b]. Then set m = average(lambda t: t**p, 0, 1) with p = 3.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write rc_corner(R, C, unit="Hz") returning the corner frequency in hertz, or when unit="rad/s". Set fc = rc_corner(R, C) and wc = rc_corner(R, C, unit="rad/s").
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write make_divider(R1, R2) that returns a function: given a source voltage, that function returns the divider's output . Then set div = make_divider(R1, R2) for R1 = 3900 Ω and R2 = 1500 Ω, and out = div(Vs) for Vs = 12 V.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
What does this print?
x = 1
def f():
x = 2
return x
f()
print(x)Explain why
Why is it useful that a function can take another function as an argument?
It lets you write a method once and use it on any problem. A routine that averages, integrates or finds the root of a function only needs to be able to evaluate the function at some points; it doesn't need to know what the formula is. Passing the formula in as an argument separates the general method from the particular problem, so one well-tested root finder serves every equation you'll ever need to solve.
Practice
Keep practicing
7 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.