Composition and Inverse Functions
Functions can be combined like numbers: added, multiplied, and, most importantly, chained so that the output of one becomes the input of the next. Some functions can also be run backwards. This lesson covers composition and inverses, the two operations behind data pipelines and encode/decode pairs.
Arithmetic of functions
For functions and , define new functions point by point:
The domain of each is the overlap of the two domains (minus the zeros of for the quotient).
Composition
The composition (" after ") feeds into , then feeds the result into :
Its domain is the set of in the domain of for which is in the domain of . Order matters: usually .
Example. and .
Going the other way, decomposing a complicated function into simple steps is a key skill for the chain rule in calculus: is with and .
import sympy as sp
x = sp.Symbol("x", real=True)
f = lambda u: sp.sqrt(u)
g = lambda u: u - 3
print("f(g(x)) =", f(g(x)), " g(f(x)) =", g(f(x)))
print("f(g(12)) =", f(g(12)), " g(f(12)) =", g(f(12)))
def compose(*fs):
"""compose(f, g, h)(x) == f(g(h(x)))"""
def h(v):
for fn in reversed(fs):
v = fn(v)
return v
return h
p = compose(lambda u: u**5, lambda u: 2*u + 1)
print("(2x+1)^5 at x = 1:", p(1))f(g(x)) = sqrt(x - 3) g(f(x)) = sqrt(x) - 3
f(g(12)) = 3 g(f(12)) = -3 + 2*sqrt(3)
(2x+1)^5 at x = 1: 243
Inverse functions
A function is one-to-one if different inputs always give different outputs. Graphically, every horizontal line meets the graph at most once (the horizontal line test). Exactly the one-to-one functions have an inverse , which undoes :
Note: is not . The means "inverse function", as in .
Finding an inverse. Write , solve for , then swap the names.
Check: . ✓
Graph. Swapping and reflects the graph across the line . If is on , then is on .
Restricting the domain. is not one-to-one on , but on it is, and its inverse there is . This is exactly how and were defined in Inverse Trigonometric Functions, and how is the inverse of in the next lessons.
import sympy as sp
x, y = sp.symbols("x y", real=True)
f = (3*x - 2) / 5
inv = sp.solve(sp.Eq(y, f), x)[0].subs(y, x)
print("f⁻¹(x) =", inv)
print("f⁻¹(f(x)) =", sp.simplify(inv.subs(x, f)))
g = x**3 + 1
roots = sp.solve(sp.Eq(y, g), x)
print("inverse of x³+1:", roots[0], f"(plus {len(roots) - 1} complex roots)")
print("inverse of x² (two branches):", sp.solve(sp.Eq(y, x**2), x))f⁻¹(x) = 5*x/3 + 2/3
f⁻¹(f(x)) = x
inverse of x³+1: (y - 1)**(1/3) (plus 2 complex roots)
inverse of x² (two branches): [-sqrt(y), sqrt(y)]
For , solve finds all three complex cube roots; the real one, printed as (y - 1)**(1/3), is the inverse . (SymPy writes it with a fractional power, which it only treats as real for ; mathematically works for every .) For it returns two branches, which is SymPy telling you that is not one-to-one.
In software
- Pipelines are compositions. A Unix pipe
cat log | grep ERROR | wc -l, a pandas method chain, middleware in a web server and the layers of a neural network are all . Keeping each step pure makes the whole chain predictable. The order matters just as in math: normalising then rounding is not rounding then normalising. - Encode/decode pairs are inverse functions. base64 encode/decode, JSON serialise/parse, compression/decompression and encryption/decryption must satisfy
decode(encode(x)) == x. That equation is the standard round-trip test. - Not everything is invertible. A hash function is deliberately not one-to-one in a recoverable way, and lossy compression (JPEG, MP3) throws information away, so no exact inverse exists.
- Unit conversions like °C ↔ °F or pixels ↔ world coordinates are inverse pairs (screen to world).
import base64
import json
def caesar(shift):
return lambda s: "".join(chr((ord(c) - 97 + shift) % 26 + 97) if c.islower() else c for c in s)
encode, decode = caesar(3), caesar(-3)
msg = "attack at dawn"
print(encode(msg), "->", decode(encode(msg)))
b = base64.b64encode(msg.encode())
print(b.decode(), "->", base64.b64decode(b).decode())
data = {"id": 7, "tags": ["a", "b"]}
print("round trip ok:", json.loads(json.dumps(data)) == data)
c_to_f = lambda c: c * 9 / 5 + 32
f_to_c = lambda f: (f - 32) * 5 / 9
print("37 °C =", c_to_f(37), "°F, back:", f_to_c(c_to_f(37)))dwwdfn dw gdzq -> attack at dawn
YXR0YWNrIGF0IGRhd24= -> attack at dawn
round trip ok: True
37 °C = 98.6 °F, back: 37.0
Exercises
Exercise 1: Compose
With and , find , and both at .
Answer
, ; at : 11 and 1.
Solution
Exercise 2: Domain of a composition
Let and . Find and its domain, and and its domain.
Answer
, . , .
Solution
needs , i.e. . needs in the domain of , i.e. ; accepts every real.
Exercise 3: Find an inverse
Find the inverse of , , and state its domain.
Answer
, domain .
Solution
The range of excludes 1 ( would need ), so has domain .
f = lambda x: (x + 1) / (x - 2)
finv = lambda x: (2 * x + 1) / (x - 1)
print([round(finv(f(v)), 12) + 0.0 for v in (-3, 0, 5, 10)])[-3.0, 0.0, 5.0, 10.0]
Exercise 4: Restrict to invert
is not one-to-one. Restrict it to a domain where it is, and find the inverse there.
Answer
On : , for .
Solution
The vertex is at , so the right half is increasing.
Exercise 5: Pipeline and round trip
Write pipeline = compose(str.strip, str.lower)-style code that normalises a username (strip spaces, lowercase, then replace spaces with "_"), apply it to " Ada Lovelace ", and explain why this pipeline has no inverse.
Answer
Result: ada_lovelace. It is not one-to-one: "ADA lovelace" and " ada lovelace" give the same output, so the original cannot be recovered.
Solution
def compose(*fs):
def h(v):
for fn in reversed(fs):
v = fn(v)
return v
return h
normalise = compose(lambda s: s.replace(" ", "_"), str.lower, str.strip)
print(normalise(" Ada Lovelace "), normalise("ADA lovelace"))ada_lovelace ada_lovelace
Test yourself
If and , what is ?
- 6
- 7
- 9
- 12
Which function has an inverse on all of ?
A test checks decode(encode(x)) == x for many x. In math terms it checks that…
- encode is even
- decode is a left inverse of encode
- is constant
- encode is periodic