Sub topic 3
Why the Order of Composition Matters
Assume you already know function notation and the basic idea of composition. A composition combines two functions by using the output of one function as the input of another.
For functions \(f\) and \(g\), the composition \(f \circ g\) is defined by
\[ (f \circ g)(x) = f(g(x)). \]
Read this as “\(f\) composed with \(g\).” The function nearest to \(x\), \(g\), acts first. Then \(f\) acts on the result.
The order changes the result
Consider
\[ f(x)=2x+3 \]
and
\[ g(x)=x^2. \]
For \(f \circ g\), apply \(g\) first:
\[ (f\circ g)(x)=f(g(x))=f(x^2)=2x^2+3. \]
For \(g \circ f\), apply \(f\) first:
\[ (g\circ f)(x)=g(f(x))=g(2x+3)=(2x+3)^2. \]
These expressions are different. At \(x=4\),
\[ (f\circ g)(4)=2(4^2)+3=35, \]
but
\[ (g\circ f)(4)=(2\cdot4+3)^2=121. \]
Function composition is therefore generally not commutative. In other words,
\[ f\circ g \ne g\circ f \]
for most pairs of functions.
def f(x):
return 2 * x + 3
def g(x):
return x ** 2
def compose(outer, inner):
return lambda x: outer(inner(x))
f_after_g = compose(f, g)
g_after_f = compose(g, f)
print(f_after_g(4)) # 35
print(g_after_f(4)) # 121The compose function takes the function that acts later as outer and the function that acts first as inner. Its returned function follows the pattern outer(inner(x)).
A useful way to track the order
Write the input and output at each stage:
\[ x \longrightarrow g(x) \longrightarrow f(g(x)). \]
For the reverse composition, the path changes:
\[ x \longrightarrow f(x) \longrightarrow g(f(x)). \]
The order can also affect the domain of a composition. For example, if an outer function accepts only nonnegative inputs, then the inner function must produce nonnegative values. Thus, when finding the domain of \(f\circ g\), check both the domain of \(g\) and whether \(g(x)\) belongs to the domain of \(f\).
When can the order stay the same?
Some special functions do commute. If \(f(x)=x+2\) and \(g(x)=x+3\), then
\[ f(g(x))=x+5=g(f(x)). \]
This happens because adding 2 and adding 3 can occur in either order. However, this is a special property, not a rule for composition.
Exercise
Let f(x) = x - 4 and g(x) = 3x. Find (f ∘ g)(x), (g ∘ f)(x), and evaluate both at x = 2.
Show answer
(f ∘ g)(x) = 3x - 4, so (f ∘ g)(2) = 2. (g ∘ f)(x) = 3x - 12, so (g ∘ f)(2) = -6.