Mathematical Foundations

I.5 · Mathematical Language

What does a function do with one input?

A function is a machine: one input goes in, steps are carried out in a fixed order, and exactly one output comes out. We follow a value through each step, find the inputs a machine refuses, ask which inputs give a chosen output, wire two machines together in both orders, and run a machine backwards.

A function as a machine: x  ⟼  f(x)x\;\longmapsto\;f(x)

Try a machine

A graph of y equals the square of x minus 2, drawn as a curve over the x-axis. The inputs the machine accepts are all real numbers; the outputs it can give are all numbers greater than or equal to 0. The marker at x equal to 4 has height 4.

shift
2
input
4
after step 1: subtract 2
2
after step 2: square
4
output
4
every input the machine accepts
ℝ
every output it can give
[0, ∞)
one-to-one: different inputs always give different outputs?
no

= exact · ≈ rounded to 6 decimals · the domain is every input the machine accepts, the image every output it can give

  1. input x44
  2. subtract 2
  3. 22
  4. square
  5. output f(x)44

With f(x) = (x − 2)², the machine takes x = 4 and subtracts 2 to get 2, then squares it to get 4. The output is f(4) = 4: exactly one output for this one input.

Some inputs and the outputs the machine gives. The current input is highlighted.
input xxoutput f(x)f(x)
−3-32525
−2-21616
−1-199
0044
1111
2200
3311
4444
f(x)=(x−2)2\begin{aligned}f(x)&=\left(x-2\right)^{2}\end{aligned}
f(4)=(4−2)2=22=4\begin{aligned}f\left(4\right)&=\left(4-2\right)^{2}\\&=2^{2}\\&=4\end{aligned}
Rule

from −5 to 5, whole numbers only

from −6 to 6, up to 2 decimal places

A machine with a rule, an input and an output. Choose a rule, set its number a, then drag the point along the curve or type an input x. The boxes show every step the machine takes, the dashed lines on the graph show the input and the output, and the table lists some inputs and outputs. Try the rule 1/(x − a) at x = a, and the square root at an input below −a.

Try it before reading on. Leave the rule at “subtract 2, then square” and move the input to 44: the boxes read 44, then 22, then 44. Now move the input to 00. The output is the same, 44. Two different inputs gave one output, and that is allowed. Then pick the rule x+a\sqrt{x+a} and drag the input to the left of −3-3: the machine stops at the square root and the point leaves the graph. By the end of the chapter you will know what a function is, how to find the inputs it accepts and the outputs it can give, how to chain two functions, and when a function can be run backwards.

Intuition: a machine with one slot

Think of a vending machine that takes one coin and gives one item. It does not matter how it works inside; what matters is the behaviour: put in the same coin and you get the same item, and there is never a coin that gives two items at once. A function is the mathematical version. It takes one input, performs a sequence of steps, and gives one output.

The picture of a pipeline is more than a metaphor. The rule f(x)=(x−2)2f(x)=(x-2)^{2} is not a mysterious symbol; it is two instructions in order: subtract 22, then square. Evaluating f(4)f(4) means carrying them out on 44: 4−2=24-2=2, then 22=42^{2}=4. Reading a formula as a list of steps is the habit that this chapter builds, because every question about functions is a question about a step.

  • What can go in? Some steps refuse some values: you cannot divide by 00 or take the square root of a negative number. The inputs the whole machine accepts form its domain.
  • What can come out? The outputs that really occur form the image.
  • Which inputs give this output? Asking this runs the machine backwards. Sometimes there is one answer, sometimes two, sometimes none.
  • What if I wire two machines together? The output of the first becomes the input of the second. The order matters.

This chapter uses the equations of the previous chapter (to find which inputs give an output you solve an equation, and to run a machine backwards you undo its steps in reverse order), the coordinate plane of the second chapter (the graph), and the squares and roots of the first.

Definition: function, domain, image, graph

Function. A function ff from a set AA to a set BB is a rule that assigns to every element xx of AA exactly one element f(x)f(x) of BB. We write f ⁣:A→Bf\colon A\to B and x↦f(x)x\mapsto f(x), and read f(x)f(x) as ”ff of xx” (the output of ff for the input xx). It is not the product of ff and xx.

Domain and codomain. AA is the domain: the inputs the function is defined on. BB is the codomain: the set the outputs are drawn from. A function is not just a formula; the formula together with its domain is what makes it a function. When no domain is stated, we take the largest set of real numbers for which every step can be carried out.

Image. The image of ff is the set of outputs that actually occur, {f(x)∣x∈A}\{f(x)\mid x\in A\}. It can be smaller than the codomain. For f(x)=x2f(x)=x^{2} with codomain R\R the image is [0,∞)[0,\infty), because no square is negative.

Graph. The graph of ff is the set of points (x,f(x))(x,f(x)) in the plane. A curve is the graph of a function exactly when every vertical line meets it at most once (the vertical line test): a second point above the same xx would be a second output.

Preimage. For a number hh, the inputs xx with f(x)=hf(x)=h are the preimages of hh. There can be none, one, or several. Finding them means solving the equation f(x)=hf(x)=h.

One-to-one and onto. ff is one-to-one (injective) when different inputs always give different outputs: no output has two preimages. ff is onto its codomain when every element of the codomain is an output: every output has at least one preimage. On a graph, “one-to-one” is the horizontal line test: every horizontal line meets the curve at most once.

Composition. For g ⁣:A→Bg\colon A\to B and f ⁣:B→Cf\colon B\to C, the composite f∘gf\circ g is the function x↦f(g(x))x\mapsto f(g(x)): apply gg first, then ff. Read it right to left.

Inverse. If ff is one-to-one with image BB, its inverse f−1 ⁣:B→Af^{-1}\colon B\to A sends each output back to the one input that produced it, so f−1(f(x))=xf^{-1}(f(x))=x and f(f−1(y))=yf(f^{-1}(y))=y. The inverse exists exactly when ff is one-to-one onto its image. The notation f−1f^{-1} is not 1/f1/f.

Reading a rule as a pipeline

The stage at the top offers six rules, each one or two steps:

rulesteps, in orderdomainimage
axax (a≠0a\neq0)multiply by aaR\RR\R
ax2ax^{2}square, then multiply by aaR\R[0,∞)[0,\infty) if a>0a>0, (−∞,0](-\infty,0] if a<0a<0
(x−a)2(x-a)^{2}subtract aa, then squareR\R[0,∞)[0,\infty)
x+a\sqrt{x+a}add aa, then take the square root[−a,∞)[-a,\infty)[0,∞)[0,\infty)
1x−a\dfrac{1}{x-a}subtract aa, then take the reciprocalevery real number except aaevery real number except 00
∣x−a∣\lvert x-a\rvertsubtract aa, then take the absolute valueR\R[0,∞)[0,\infty)

For a=0a=0 the multiplier rules become the constant 00 with domain R\R and image {0}\{0\}.

The stage keeps every number exact: 2\sqrt{2} stays 2\sqrt{2} and 1/31/3 stays 1/31/3, and the inspector says whether a value is exact or a rounded decimal. One flat state, the rule, the number aa and the input xx, produces everything you see: the boxes, the point, the dashed lines, the table and the verdict. Dragging the point changes only xx, so the curve itself does not move; changing aa or the rule redraws it.

When a step refuses, the pipeline stops there. The boxes after the refusal are marked “not reached”, the point drops to the xx-axis, and the verdict names the step and the reason. A function has no output at such an input; it is not “zero” and not “infinity”.

The shape of a shift

Compare x2x^{2} with (x−2)2(x-2)^{2}. The second is the first with the input moved before squaring: the machine subtracts 22, so the input must be 22 larger to reach the same value. The graph moves to the right by 22, which feels backwards at first because of the minus sign. Test with the output 00: (x−2)2=0(x-2)^{2}=0 when x=2x=2.

Domain: where the machine refuses

A step refuses an input when it has no answer. There are two refusals in this chapter:

  • the reciprocal of 00 (no number multiplied by 00 gives 11), and
  • the square root of a negative number (no real number squared is negative).

The domain of the whole machine is the set of inputs that no step refuses. Two ways to find it:

  1. Forwards: try an input and watch the pipeline, as the first stage does.
  2. Backwards: start from the last step and ask what it needs. x+3\sqrt{x+3} needs x+3≥0x+3\ge0, that is x≥−3x\ge-3; the set [−3,∞)[-3,\infty) contains −3-3 because 0=0\sqrt{0}=0. 1x−2\dfrac{1}{x-2} needs x−2≠0x-2\neq0, that is x≠2x\neq2. For a machine with two steps, pull the requirement of the last step back through the first.

The domain is the input side of the graph, the set of xx values that have a curve above or below them. At the edge of x+3\sqrt{x+3} the curve starts with a filled dot at (−3,0)(-3,0); at x=2x=2 the curve of 1x−2\dfrac{1}{x-2} has a gap, with a vertical dashed line (an asymptote) showing where it blows up.

A formula is not yet a function

The formulas x2−4x−2\dfrac{x^{2}-4}{x-2} and x+2x+2 agree at every x≠2x\neq2, and at x=2x=2 the first divides by 00 while the second gives 44. They are different functions because their domains differ. Cancelling the common factor (x−2)(x-2) is the same step that lost a root in the previous chapter: it is legal only where the factor is not 00.

Domain, image and the inputs that give an output

Fix a height hh and ask: which inputs xx give f(x)=hf(x)=h? On the graph, draw the horizontal line at height hh and read the xx where it meets the curve.

Which inputs give this output? f(x)=hf(x)=h

Try an equation

A graph of y equals the square of x minus 2, with a horizontal line at height 4. The line meets the curve at 2 points. The part of the x-axis the machine accepts is all real numbers; the part of the y-axis it reaches is all numbers greater than or equal to 0.

shift
2
height of the line (an output)
4
how many inputs x give f(x) = h
2 inputs
input 1
0
input 2
4
every input the machine accepts
ℝ
every output it can give
[0, ∞)
one-to-one: different inputs always give different outputs?
no
every real number is an output?
no

= exact · ≈ rounded to 6 decimals · f is one-to-one when no output has two inputs

The line y = 4 meets the graph at two points: the inputs x₁ = 0 and x₂ = 4 both give the output 4. A function may send two inputs to one output (never one input to two outputs), but then it is not one-to-one. The image of f is [0, ∞), not all of ℝ, so f is not onto ℝ.

(x−2)2=4⇒ x−2=±4⇒ x1=0,  x2=4\begin{aligned}&\left(x-2\right)^{2}=4\\&\Rightarrow\ x-2=\pm\sqrt{4}\\&\Rightarrow\ x_{1}=0,\ \ x_{2}=4\end{aligned}
domain=Rimage=[0, ∞)\begin{aligned}\text{domain}&=\R\\\text{image}&=[0,\,\infty)\end{aligned}
Rule

from −5 to 5, whole numbers only

from −6 to 6, up to 2 decimal places

The graph of a rule and a horizontal line at height h. Drag the handle on the right up or down, or type h. The marked points are the inputs that give the output h. The bar on the x-axis is the domain and the bar on the y-axis is the image; a hollow end is not included. Try (x − 2)² with h = 4, 0 and −1, and 1/(x − 2) with h = 0.

With (x−2)2(x-2)^{2} the line at h=4h=4 meets the curve twice, at x=0x=0 and x=4x=4: both satisfy (x−2)2=4(x-2)^{2}=4, because x−2=±2x-2=\pm2. At h=0h=0 it touches once, at x=2x=2. At h=−1h=-1 it misses, since a square is never negative: the equation has no solution. The preimages come from solving, not from reading the picture: the model solves (x−2)2=h(x-2)^{2}=h exactly as x=2±hx=2\pm\sqrt{h} for h>0h>0, and the picture confirms it.

Three consequences follow directly.

  • The image is the set of heights that the line meets. For (x−2)2(x-2)^{2} it is [0,∞)[0,\infty), the bar on the vertical axis.
  • One-to-one fails when some height meets the curve twice. (x−2)2(x-2)^{2} and ∣x∣\lvert x\rvert are not one-to-one; axax (with a≠0a\neq0), x+a\sqrt{x+a} and 1x−a\dfrac{1}{x-a} are.
  • Onto R\R fails when some height is missed. The line y=−1y=-1 misses every curve whose image is [0,∞)[0,\infty). The curve 1x−2\dfrac{1}{x-2} misses y=0y=0 as well: 11 divided by any number is never 00, so the equation 1x−2=0\dfrac{1}{x-2}=0 has no solution, and the image is R\R without 00.

An important distinction: a function may send two inputs to one output (the horizontal line meets twice), but it may never send one input to two outputs (the vertical line would meet twice). The first is the case of (x−2)2(x-2)^{2}; the second is not a function at all.

Composition: one machine after another

Let f(x)=x2f(x)=x^{2} and g(x)=2x−1g(x)=2x-1. The composite f∘gf\circ g means first gg, then ff: f(g(x))=(2x−1)2f(g(x))=(2x-1)^{2}. The composite g∘fg\circ f means first ff, then gg: g(f(x))=2x2−1g(f(x))=2x^{2}-1. At x=3x=3 the first gives g(3)=5g(3)=5 and f(5)=25f(5)=25; the second gives f(3)=9f(3)=9 and g(9)=17g(9)=17. Composition is not commutative: the order is part of the answer. The stage starts at x=0x=0, where f(g(0))=(−1)2=1f(g(0))=(-1)^{2}=1 but g(f(0))=2⋅0−1=−1g(f(0))=2\cdot0-1=-1. The graph shows heights from −6-6 to 66, so at x=3x=3 the heights 2525 and 1717 are beyond its top edge: the stage then says so and gives the exact numbers beside the graph instead of drawing a dot.

Two machines in a row: f∘gf\circ g and g∘fg\circ f

Try a pair

A graph with two curves: y equals f of g of x, which is x squared applied after 2 x minus 1, and y equals g of f of x, the other order. At x equal to 0 the heights are 1 and minus 1.

input
0
g first: 2x − 1
−1
f ∘ g: g first, then f
1
f first: x²
0
g ∘ f: f first, then g
−1
inputs the composite f ∘ g accepts
ℝ
inputs the composite g ∘ f accepts
ℝ

= exact · ≈ rounded to 6 decimals · f ∘ g means g first, then f

f ∘ g: g first, then f

  1. input x00
  2. multiply by 2
  3. 00
  4. subtract 1
  5. g(x)−1-1
  6. square
  7. f(g(x))11

g ∘ f: f first, then g

  1. input x00
  2. square
  3. f(x)00
  4. multiply by 2
  5. 00
  6. subtract 1
  7. g(f(x))−1-1

At x = 0, f(g(x)) = 1 but g(f(x)) = −1. The order matters: f ∘ g sends x through g first, g ∘ f through f first. These are different machines.

Domain of f ∘ g: ℝ

Domain of g ∘ f: ℝ

f(x)=x2,g(x)=2x−1f(g(x))=(2x−1)2g(f(x))=2(x2)−1\begin{aligned}f(x)&=x^{2},\quad g(x)=2x-1\\f(g(x))&=\left(2x-1\right)^{2}\\g(f(x))&=2\left(x^{2}\right)-1\end{aligned}
f(g(0))=f(−1)=1g(f(0))=g(0)=−1\begin{aligned}f\left(g\left(0\right)\right)&=f\left(-1\right)=1\\g\left(f\left(0\right)\right)&=g\left(0\right)=-1\end{aligned}
f is
g is

from −6 to 6, up to 2 decimal places

Two machines, f and g, and an input x. The solid curve is f after g, the dashed curve is g after f. The two rows of boxes show every value, and the number lines show the domain of each composite. Try the presets: x² after 2x − 1 at 0 and at 1, the square root after 2x − 1 at 0, and 1/x after 1/x.

At x=1x=1 the two orders happen to agree (both give 11). Setting (2x−1)2=2x2−1(2x-1)^{2}=2x^{2}-1 and simplifying gives 2x2−4x+2=02x^{2}-4x+2=0, that is 2(x−1)2=02(x-1)^{2}=0, so x=1x=1 is the only input where they agree: agreement at one input does not make the two functions equal.

The domain of a composite

A composite can accept fewer inputs than its inner function. Take f(x)=xf(x)=\sqrt{x} and g(x)=2x−1g(x)=2x-1. The function gg accepts every real number, but f∘gf\circ g needs the output of gg to be allowed in ff: 2x−1≥02x-1\ge0, so x≥12x\ge\tfrac12. The input x=0x=0 is accepted by gg, gives −1-1, and the square root refuses it. In the stage the composite f∘gf\circ g at 00 is marked undefined while g∘fg\circ f is fine. The domain of a composite is the part of the inner function’s domain whose outputs the outer function accepts.

A second trap: x2\sqrt{x^{2}} is not xx. At x=−3x=-3 the square gives 99 and the root gives 33, so x2=∣x∣\sqrt{x^{2}}=\lvert x\rvert. Choose f=xf=\sqrt{x} and g=x2g=x^{2} and set the input to −3-3 to see it.

Running a machine backwards: the inverse

To find the inverse of y=2x−1y=2x-1, solve for xx: add 11 to both sides, then divide by 22. The inverse is x=y+12x=\dfrac{y+1}{2}. Its steps are the original steps undone in the opposite order (the last step is undone first), and each undoing step is a balanced step from the previous chapter.

Running a machine backwards: f−1f^{-1}

Try a machine

A graph of y equals 2 x minus 1, the dashed line y equals x, and the mirror image of the curve in that line. The mirror image of the curve in the dashed line y equals x is the graph of the inverse. The point x equal to 3, y equal to 5 and its mirror image are marked.

input
3
output
5
is there an inverse function?
yes
the inverse applied to the output
3
the round trip returns the input
yes
domain of f
ℝ
image of f (domain of the inverse)
ℝ

= exact · ≈ rounded to 6 decimals · the inverse needs one input for every output

Forward: x to y

  1. input x33
  2. multiply by 2
  3. 66
  4. subtract 1
  5. output y55

Backward: y to x

  1. input y55
  2. add 1
  3. 66
  4. multiply by 0.5
  5. output x33

f(3) = 5, and the inverse sends 5 back to 3. The round trip f⁻¹(f(x)) returns x = 3 exactly. On the graph, (3, 5) and (5, 3) are mirror images in the line y = x.

y=2x−1x=y+12\begin{aligned}&y=2x-1\\&x=\dfrac{y+1}{2}\end{aligned}
f(3)=5f−1(5)=3\begin{aligned}f\left(3\right)&=5\\f^{-1}\left(5\right)&=3\end{aligned}
Function

from −6 to 6, up to 2 decimal places

A function, its graph (solid), the dashed line y = x and the mirror image of the graph in that line. The boxes run the machine forwards and then the inverse backwards. Pick the function and the input. For x² choose whether every real input is allowed or only x at least 0, and see when the mirror image stops being a function.

The graph of the inverse is the mirror image of the graph of ff in the line y=xy=x. Swapping the roles of input and output swaps the coordinates of every point: if (3,5)(3,5) is on the graph of 2x−12x-1, then (5,3)(5,3) is on the graph of its inverse. In the stage the filled dot is (x,y)(x,y) and the hollow dot is its mirror image (y,x)(y,x).

Not every function has an inverse. On all of R\R the square sends 33 and −3-3 to the same output 99. A backward machine fed with 99 would have to return both, and a function returns only one value. The mirror image of the parabola is a parabola on its side, which fails the vertical line test. The fix is to restrict the domain: if only x≥0x\ge0 is allowed, 33 is the single preimage of 99 and the inverse is the square root. A function has an inverse exactly when it is one-to-one (on the domain you chose), and the domain of the inverse is the image of the original. That is why restricting the inputs is not cheating: it changes the function.

Also look at x\sqrt{x} and 1x\dfrac{1}{x}. The inverse of x\sqrt{x} is the square y2y^{2} for y≥0y\ge0. The reciprocal is its own inverse: 11/x=x\dfrac{1}{1/x}=x, so its graph is its own mirror image in y=xy=x.

Worked examples

Five complete solutions, each one a list of steps with the reason for each. They use only what this chapter defines, and each number you see is computed by the same model as the stages.

Worked examples: solve, then check

Choose a problem

f(x)=(x−2)2f(x)=\left(x-2\right)^{2}

A function is a rule that sends every input to exactly one output. This one says: subtract 2, then square.

Choose a problem and step through the work: evaluate a function, find a domain, find an image, compose two functions, invert a function. Going back selects an earlier step; nothing is undone.

Executable reference code

Run the Python examples below to follow the calculations step by step. First, functions as values: evaluate, compose, tabulate and invert.

code/python/functions_basic.pya function as a value, composition, a table, a round trip
# A function is a rule that sends every input to exactly one output. In Python a function is also a value: it can be passed
# to another function, stored in a list, or returned.
def shifted_square(x):
    return (x - 2) ** 2  # subtract 2, then square


def square(x):
    return x**2


def line(x):
    return 2 * x - 1


def compose(outer, inner):
    """outer after inner: the output of `inner` becomes the input of `outer`."""
    return lambda x: outer(inner(x))


print(shifted_square(-1), shifted_square(5))  # 9 9: two different inputs may share one output
print(compose(square, line)(3), compose(line, square)(3))  # 25 17: the order of the machines matters

inputs = list(range(-3, 4))
table = [(x, shifted_square(x)) for x in inputs]
print(table)  # [(-3, 25), (-2, 16), (-1, 9), (0, 4), (1, 1), (2, 0), (3, 1)]
outputs = {y for _, y in table}
print(len(outputs), len(inputs))  # 6 7: fewer outputs than inputs, so the rule is not one-to-one and cannot be undone


# 2x - 1 multiplies by 2 and then subtracts 1. Its inverse undoes the steps in the opposite order: add 1, then halve.
def undo_line(y):
    return (y + 1) / 2


print(undo_line(line(3)))  # 3.0: the round trip returns the input

Then the domain. Python raises an exception exactly where the mathematics has no value, and NumPy returns nan instead, so the domain has to be written down.

code/python/functions_domain.pywhere a machine refuses: exceptions, and masks in NumPy
import math

import numpy as np


# The domain of a function is the set of inputs for which the machine can finish. Python tells you the moment it cannot:
# a division by zero or a square root of a negative number raises an exception instead of returning a number.
def reciprocal_shift(x):
    return 1 / (x - 2)  # undefined where x - 2 = 0


def root_shift(x):
    return math.sqrt(x + 3)  # undefined where x + 3 < 0


def defined(f, x):
    try:
        f(x)
    except (ZeroDivisionError, ValueError):
        return False
    return True


print([defined(reciprocal_shift, x) for x in (0, 1, 2, 3)])  # [True, True, False, True]: only x = 2 is refused
print([defined(root_shift, x) for x in (-4, -3, 0)])  # [False, True, True]: the edge x = -3 belongs to the domain

try:
    math.sqrt(-1)
except ValueError as error:
    print(error)  # math domain error

# The domain of a composite is smaller than the domain of the inner function: sqrt(2x - 1) needs 2x - 1 >= 0, so x >= 1/2.
print([defined(lambda x: math.sqrt(2 * x - 1), x) for x in (0, 0.5, 1)])  # [False, True, True]

# NumPy applies the rule to a whole array. Invalid inputs become nan (not a number) rather than raising, so state the
# domain yourself with a mask, and say what to do outside it.
x = np.array([-4.0, -3.0, 0.0, 5.0])
inside = x + 3 >= 0
y = np.where(inside, np.sqrt(np.where(inside, x + 3, 0.0)), np.nan)
print(y.tolist())  # [nan, 0.0, 1.7320508075688772, 2.8284271247461903]
print(inside.tolist())  # [False, True, True, True]

Finally the machine-learning picture: a model is a function of its input and of its parameters, the loss is a function of the parameters, and a layer is a composition.

code/python/functions_params.pya model f(x; w, b), a loss L(w, b), a layer as a composition
# A model is a function of an input x that also depends on parameters: here f(x; w, b) = w*x + b. Training chooses the parameters,
# so the LOSS is a second function, this time of (w, b), with the data held fixed.
def model(x, w, b):
    return w * x + b


data = [(0, 1), (1, 3), (2, 5), (3, 7)]  # these points lie exactly on y = 2x + 1


def loss(w, b):
    """Mean squared error of the model on the data, as a function of the parameters."""
    return sum((model(x, w, b) - y) ** 2 for x, y in data) / len(data)


print(loss(2, 1))  # 0.0: the right parameters
print(loss(1, 1))  # 3.5: errors 0, -1, -2, -3 give (0 + 1 + 4 + 9) / 4
print(loss(2, 0))  # 1.0: every prediction is 1 too low


# A neural-network layer is a composition: an affine map followed by an activation function.
def relu(z):
    return max(z, 0.0)


def make_layer(w, b):
    return lambda x: relu(model(x, w, b))


layer = make_layer(2.0, 1.0)
print(layer(-1.0), layer(2.0))  # 0.0 5.0: 2*(-1) + 1 = -1 is clipped to 0, and 2*2 + 1 = 5 passes through
print(relu(-3.0), relu(-1.0))  # 0.0 0.0: two inputs, one output, so relu cannot be undone

Two remarks on the first file. compose(outer, inner) returns a new function: in Python a function is an ordinary value, which is what makes composition a one-line definition. And len(outputs) < len(inputs) is a finite version of “not one-to-one”: if the number of distinct outputs is smaller than the number of inputs, two inputs must share an output.

Explore: change the parameters

These questions have definite answers; check them against the stages.

  • On the first stage choose (x−a)2(x-a)^{2} with a=2a=2. Find two inputs between −3-3 and 77 that give the output 99. (They are −1-1 and 55.)
  • On the first stage choose x+a\sqrt{x+a} with a=3a=3. At which step does the machine stop for x=−4x=-4, and what is the largest whole-number input it refuses?
  • On the first stage choose 1x−a\dfrac{1}{x-a} with a=2a=2. Which input is refused, and what happens to the output as the input gets close to 22?
  • On the height stage choose (x−2)2(x-2)^{2}. For which heights hh does the line meet the curve twice, once, and not at all?
  • On the height stage choose ∣x−a∣\lvert x-a\rvert. Does changing aa change how many inputs a given positive height has?
  • On the composition stage choose f=x2f=x^{2} and g=2x−1g=2x-1. Slide the input and look for an input other than 11 at which the two orders give the same value. Is there one? (Solve (2x−1)2=2x2−1(2x-1)^{2}=2x^{2}-1 to check.)
  • On the composition stage choose f=xf=\sqrt{x} and g=x2g=x^{2} and set x=−3x=-3. What does the composite f∘gf\circ g give, and which familiar function is it?
  • On the inverse stage choose x2x^{2} with every real input allowed and the input 22. Which other input has the same output, and where is its dot on the graph? Then restrict the inputs to x≥0x\ge0 and see what the mirror image becomes.

Common mistakes

Numerical considerations

The mathematics above is exact. A program computes with doubles, and a composition of exact inverses is not always the identity in doubles.

Squaring a square root. (x)2\bigl(\sqrt{x}\bigr)^{2} is exactly xx for every non-negative xx. In doubles, math.sqrt(2) ** 2 is 2.0000000000000004, because the root is rounded to the nearest double before it is squared. The reciprocal of a reciprocal is rounded twice: 1 / (1 / 49) is 49.00000000000001. And near a pole the cancellation in x−2x-2 turns a tiny rounding error into a huge relative error. The table feeds the machine 2+10−k2+10^{-k} and prints the exact answer, which is 10k10^{k}, next to the double the program holds.

computationPythonexact valuedouble (what the program holds)agree?
square of the root of 2math.sqrt(2) ** 222.0000000000000004⚠ no
square of the root of 3math.sqrt(3) ** 232.9999999999999996⚠ no
square of the root of 5math.sqrt(5) ** 255.000000000000001⚠ no
square of the root of 10math.sqrt(10) ** 21010.000000000000002⚠ no
reciprocal of the reciprocal of 491 / (1 / 49)4949.00000000000001⚠ no
reciprocal of the reciprocal of 981 / (1 / 98)9898.00000000000001⚠ no
1/(x − 2) at x = 2 + 1e-11 / ((2 + 1e-1) - 2)109.999999999999991⚠ no
1/(x − 2) at x = 2 + 1e-51 / ((2 + 1e-5) - 2)10000099999.99999934487⚠ no
1/(x − 2) at x = 2 + 1e-101 / ((2 + 1e-10) - 2)100000000009999999172.59636⚠ no
1/(x − 2) at x = 2 + 1e-151 / ((2 + 1e-15) - 2)10000000000000001125899906842624⚠ no
1/(x − 2) at x = 2 + 1e-161 / ((2 + 1e-16) - 2)10000000000000000ZeroDivisionError⚠ no

The domain does not announce itself in NumPy. math.sqrt(-1) raises a ValueError, but np.sqrt(-1.0) returns nan with only a warning, and nan then flows through every later step. The reference file masks the invalid inputs explicitly and says what to put there. A nan in a loss is nearly always a domain error upstream: a sqrt, a log or a division that received an input outside its domain.

Inverses are only as exact as the data. Undoing a transformation with its inverse, such as unstandardising a feature, can differ from the original in the last digit; compare with a tolerance (math.isclose), not ==.

Connections to engineering and machine learning

  • A model is a function of its input and its parameters. A linear model f(x;w,b)=wx+bf(x;w,b)=wx+b takes an input xx and has parameters ww and bb. Training does not change xx; it chooses (w,b)(w,b). The reference file computes the loss as a second function, now of the parameters, with the data held fixed: the loss is 00 at (2,1)(2,1), 3.53.5 at (1,1)(1,1) and 11 at (2,0)(2,0).
  • A network is a composition. A layer applies an affine map and then an activation function, and a deep network composes many layers. The order matters for the reason in this chapter: g∘fg\circ f and f∘gf\circ g are different functions.
  • Activations and invertibility. The ReLU function, max⁡(z,0)\max(z,0), sends all negative numbers to 00, so it is not one-to-one and cannot be undone: information is lost. The reference file shows relu(-3.0) and relu(-1.0) both giving 0.0.
  • Domains in code. The functions x\sqrt{x}, log⁡x\log x and 1/x1/x all have restricted domains. Machine learning code guards them (np.maximum(x, eps), masks, clipped probabilities) because a single input outside the domain turns into nan or inf.
  • Undoing a transformation. Standardising a feature is an invertible function of the data. Its inverse exists when the scale is not 00, which is the restriction that made the earlier multiplication by 00 impossible to undo. Likewise a probability can be mapped to an unbounded score and back by a pair of inverse functions, on the restricted domain where both are defined.
  • Looking ahead. The next chapter surveys the families that appear again and again (lines, powers, exponentials, logarithms and more), and each of them has a domain, an image and, sometimes, an inverse.

Exercises

Answer each question and press Check. A wrong answer tells you which mistake it looks like. After one attempt you may open a worked solution.

calculation

Evaluate a function

The machine is f(x) = (x − 3)²: subtract 3, then square. Enter f(−1).

prediction

Which way does the curve move?

The graph of f(x) = (x − a)² has its lowest point where the output is 0. When a is increased from 2 to 4, how does the whole graph move?

Choose one answer

prediction

The domain of a square root

What is the domain of f(x) = √(x + 3)? That is, for which inputs x can the machine finish?

Choose one answer

prediction

Where does the machine divide by zero?

What is the domain of f(x) = 1/(x − 2)?

Choose one answer

prediction

The image of −2x²

What is the image of f(x) = −2x², the set of all outputs the machine can give?

Choose one answer

calculation

Which inputs give the output 9?

For f(x) = (x − 2)², find ALL inputs x with f(x) = 9. Enter the smaller one and the larger one.

calculation

Which machine goes first?

Let f(x) = x² and g(x) = 2x − 1. Compute f(g(3)): g acts FIRST, then f. Enter the number.

explanation

The domain of a composite

Let f(x) = √x and g(x) = 2x − 1. For which x can the composite f(g(x)) = √(2x − 1) be computed?

Choose one answer

construction

Choose the parameter

The machine is f(x) = (x − a)². Choose a whole number a from −5 to 5 so that f(1) = 16. Either of the two possible values is accepted.

explanation

Why x² cannot be undone on ℝ

Why is there no inverse function for f(x) = x² on all real numbers?

Choose one answer

Summary and checkpoints

  • A function assigns to every input in its domain exactly one output. A formula without a domain is not yet a function; the domain is the set of inputs for which every step can be carried out.
  • Read a rule as a pipeline of steps. The two refusals are the reciprocal of 00 and the square root of a negative number; an input that is refused has no output.
  • The image is the set of outputs that occur. To find the inputs that give an output hh, solve f(x)=hf(x)=h: there may be none, one or several.
  • One input never gives two outputs; two inputs may share one. One-to-one means no output is shared (horizontal line test).
  • In f∘gf\circ g the function gg acts first. Composition is not commutative, and the domain of a composite can be smaller than the domain of the inner function.
  • An inverse undoes the steps in the opposite order. It exists exactly when the function is one-to-one; restricting the domain can create one (the square root for x2x^{2} on x≥0x\ge0). Its graph is the mirror image in y=xy=x. It is not 1/f1/f.
  • In code: write the domain down, do not compare a computed value with a pole using ==, and remember that NumPy turns domain errors into nan silently.

Checkpoints. You are ready to move on when you can, without looking:

  1. Evaluate (x−3)2(x-3)^{2} at x=−1x=-1 step by step, and say what the rule does to the input first.
  2. State the domain of x+3\sqrt{x+3} and of 1x−2\dfrac{1}{x-2}, and say which step refuses.
  3. List the inputs that give the output 99 under (x−2)2(x-2)^{2}, and the image of −2x2-2x^{2}.
  4. Compute f(g(3))f(g(3)) and g(f(3))g(f(3)) for f=x2f=x^{2} and g=2x−1g=2x-1, and say which acts first in each.
  5. Explain why x2x^{2} has no inverse on all of R\R and what restriction gives it one.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available