I.7 · Mathematical Language
Is it in, or is it out?
Almost every definition in mathematics starts by saying which things belong. Learn to combine sets, to read the ends of an interval correctly, and to describe a rule between two collections as a set of pairs.
Try it: two sets inside a universe
Or start from
Show
A Venn diagram inside the universe U, the numbers 1 to 12, with two overlapping circles A and B. Only in A: 1, 2, 3. In both: 4, 5. Only in B: 6, 7. In neither: 8, 9, 10, 11, 12. Highlighted: union, {1, 2, 3, 4, 5, 6, 7}. The picture is schematic: the areas are not to scale.
Schematic: the areas are not to scale. The box is the universe U = {1, 2, …, 12}.
- elements in A
- 5
- elements in B
- 4
- union
- {1, 2, 3, 4, 5, 6, 7}
- elements in the result
- 7
= exact (every statement about finite sets is exact)
A ∪ B = {1, 2, 3, 4, 5, 6, 7}: everything that is in A, in B, or in both. It has 7 elements.
Try it before reading on. Press overlapping, then A ∩ B: the elements that are in both sets are picked out. Press A ∪ B and the picked-out elements become everything that is in at least one of them. Now press numbers to move elements around, and watch the lists under the picture change. By the end of the chapter you will be able to say what each operation keeps, to count a union without listing it, to tell exactly when two intervals join into one, and to say which of four properties a rule between two collections has.
Intuition: a set is a question with a yes-or-no answer
A set is a collection of things, called its elements, where the only question that matters is is this thing in the set, or not? Two consequences are worth stating at once, because they surprise people who think of a set as a list. The order does not matter: and are the same set. Repeats do not matter either: writing an element twice does not make it more present, so .
Three kinds of set carry almost everything in this book:
- Finite collections, such as the rows of a dataset, the digits or the set of labels a classifier can output. You can list them and count them.
- Intervals of numbers, such as all the temperatures from to . You cannot list them, but you can say exactly where they start and stop, and whether the end itself belongs.
- Sets of pairs, such as every pair (input, output) of a function, or every pair of items that are “similar”. These are called relations.
The same few ideas apply to all three. Combine two sets by asking for what is in either, in both, in the first but not the second, or in neither. Then ask which of those are the same set, and how many elements each has.
Intervals add one genuinely new difficulty: the end. The interval of numbers strictly between and and the interval of numbers from to including both ends are different sets, and the difference is a single point on each side. That single point decides whether two intervals that touch at form one piece or two. Most mistakes with intervals are mistakes about the ends.
Definition
Sets and membership. We write when is an element of and when it is not. A set is determined by its elements: exactly when every element of is in and every element of is in . The empty set has no elements. The number of elements of a finite set is its size, written .
Subset. means every element of is in . It is a proper subset, , if in addition has an element that lacks. The empty set is a subset of every set, because the sentence every element of is in has nothing to check, so it cannot fail. Every set is a subset of itself.
The universe. To talk about “everything that is not in ” you must say everything in what. Fix a universe that contains all the elements you care about. Throughout the stages here, finite sets live in and interval sets live in the real line . A complement means nothing until the universe is named.
The operations. For two sets and inside a universe :
Here or is the inclusive or of mathematics: an element in both sets is in the union. Two sets are disjoint when .
Counting. Adding counts every element of the overlap twice, once for each set. Subtract one copy of the overlap and the count is right. This is inclusion and exclusion:
De Morgan’s laws. Complementing swaps or with and:
In words: being outside the union means being outside and outside ; being outside the intersection means being outside or outside . The stage at the top evaluates both sides for the sets you build, so you can watch them agree.
Intervals. For real numbers there are four intervals with ends and :
A square bracket means the end is included (closed); a round bracket means it is excluded (open). On a number line a closed end is drawn as a filled dot and an open end as a hollow ring. An interval can also run forever in one direction, as in or ; an infinite end is never included, because there is no number to include. If the left end is larger than the right end the set has no elements: it is the empty set. A single point is the closed interval , while and are empty.
Ordered pairs and products. An ordered pair remembers which element came first: and are different, and is allowed. The Cartesian product is the set of all ordered pairs with first element from and second from . Its size is the product of the sizes, , because the two choices are independent.
Relations. A relation from to is any subset . We write for . “Less than” on numbers is the relation ; “divides” is . A relation is nothing but its set of pairs.
Mechanics: how each piece behaves
Counting and combining finite sets
The hero stage and the full copy in Explore do the finite case. Two habits make the finite case quick:
- Draw the four regions. Two sets split the universe into four disjoint regions: in only, in both, in only, in neither. Every operation keeps a union of some of these regions: the union keeps the first three, the intersection keeps only both, the difference keeps only in only, and the complement keeps in only and in neither.
- Count by regions, not by lists. Inclusion and exclusion counts the union from three numbers. If you also know the size of the universe, the number of elements in neither set is .
Intervals: is the end in or out?
An interval is determined by four things: two ends and whether each is included. Choose them in the stage below, move the test point , and read whether belongs to each set. The result of an operation is always written in its simplest form: pieces that overlap or touch with the shared point included are merged into one, and an empty piece is dropped.
Intervals: is the end in or out?
Try these
Show
A number line from −6 to 6 with three rows. A is (0, 1). B is (1, 2). union is (0, 1) ∪ (1, 2). A filled dot marks an included end, a hollow dot an excluded end, and an arrow an end that never stops. The test point is 1.
- interval A, typed as (0, 1)
- (0, 1)
- interval B, typed as (1, 2)
- (1, 2)
- union
- (0, 1) ∪ (1, 2)
- separate pieces in the result
- 2
= exact (every end is an exact decimal, never a rounded double)
A and B meet at 1, but that point belongs to neither (it is an open end of both), so it is missing: A ∪ B = (0, 1) ∪ (1, 2) has 2 pieces, with a one-point hole.
- 1 ∉ A: it is the right end of (0, 1), and that end is open, so it is excluded.
- 1 ∉ B: it is the left end of (1, 2), and that end is open, so it is excluded.
- 1 ∉ A ∪ B: it is the right end of (0, 1), and that end is open, so it is excluded. The neighbouring piece (1, 2) is also open at 1, so 1 is a hole between them.
from −5 to 5, up to 2 decimal places
from −5 to 5, up to 2 decimal places
from −5 to 5, up to 2 decimal places
The presets are the cases that cause trouble. Read them in turn:
- : the point is in neither interval, so the union is two pieces with a one-point hole. The number line shows the hole.
- : now belongs to the first interval. The pieces meet at an included point, and the union is the single interval .
- : the intervals share exactly the point . The intersection is the one-element set , not the empty set.
- : the first interval stops just short of and the second starts at . Nothing is shared, and the intersection is empty.
- : removing a single point from the line leaves two rays, .
- shows that a difference can split an interval in two: , with the open piece cut out of the middle and both of its ends kept.
The general rule is short. Two intervals and with the same touching value make one piece if the shared point is included in at least one of them, and two pieces if it is excluded from both. The table of four cases is:
| left interval ends | right interval starts | union |
|---|---|---|
| open, | open, | two pieces, hole at |
| closed, | open, | one piece |
| open, | closed, | one piece |
| closed, | closed, | one piece (they share ) |
The complement of an interval turns every included end into an excluded one and the other way round: . The complement of the whole line is the empty set and the complement of the empty set is the whole line.
Ordered pairs and products
Choose the elements of and below. The two tables list the pairs of and of . A pair shown with a dashed outline is in one table and not in the other.
Ordered pairs: A × B and B × A
Or start from
| 3 | 4 | |
|---|---|---|
| 1 | (1,3) (only in this product) | (1,4) (only in this product) |
| 2 | (2,3) (only in this product) | (2,4) (only in this product) |
| 3 | (3,3) | (3,4) (only in this product) |
| 1 | 2 | 3 | |
|---|---|---|---|
| 3 | (3,1) (only in this product) | (3,2) (only in this product) | (3,3) |
| 4 | (4,1) (only in this product) | (4,2) (only in this product) | (4,3) (only in this product) |
A is {1, 2, 3} and B is {3, 4}. A times B has 6 ordered pairs; B times A has 6 ordered pairs.
|A × B| = 6 = |A| · |B| = 3 · 2. A × B and B × A are different sets: (1, 3) is in A × B, but it is not in B × A, because that would need 1 to be in B and 3 to be in A. Order matters in a pair.
- elements in A
- 3
- elements in B
- 2
- ordered pairs in A × B
- 6
= exact
Try the presets. For and there are pairs. The pair is in but its reverse is not in the same table, so . They are equal exactly when or when one of the sets is empty (both products are then empty). When the table is symmetric.
Relations and their four properties
A relation on a set is a subset of . Four properties tell relations apart. For all elements , , of :
- reflexive: for every (every element is related to itself);
- symmetric: implies ;
- antisymmetric: if and , then ;
- transitive: if and , then .
A property fails because of a witness: a specific pair or triple that breaks it. A property that holds has no witness. The stage finds and outlines the witness for you. The words symmetric and antisymmetric are not opposites: the equality relation is both, “less than” is antisymmetric and not symmetric, and a relation can be neither.
A relation that is reflexive, symmetric and transitive is an equivalence relation. It does what equality does: it splits the set into classes, groups of elements that are all related to one another and to nothing outside the group. “Same parity” on whole numbers is one: the classes are the odd numbers and the even numbers. A relation that is reflexive, antisymmetric and transitive is a partial order; “at most” and “divides” are examples.
A relation is a function from to when every element of is related to exactly one element of . A relation fails to be a function in two ways: some has no partner (nothing is assigned) or some has more than one (the value is ambiguous). Many different may share the same ; that does not stop it being a function.
Relations: a set of pairs
Fill the grid with the rule
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
A grid with the 4 elements of A as rows and the 4 elements of B as columns. {(1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)} are related, 6 of 16 pairs.
- all ordered pairs
- 16
- pairs in the relation
- 6
- the relation as a set of pairs
- {(1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)}
= exact
R has 6 pairs out of 16. It is not an equivalence relation: it is not reflexive and not symmetric.
What kind of relation is it?
- a R a for every a. Fails: 1 is not related to itself, (1, 1) is missing.
- a R b implies b R a. Fails: (1, 2) is in R but (2, 1) is not.
- a R b and b R a imply a = b. Holds: no two different elements are related both ways.
- a R b and b R c imply a R c. Holds: whenever a is related to b and b to c, a is related to c.
- EquivalenceIt is not an equivalence relation: it is not reflexive and not symmetric.
- FunctionNo: 1 is related to 3 elements of B (2, 3, 4), so R does not assign it a single value.
Work through these in the stage:
- less than, the relation : not reflexive (the pair is missing), not symmetric, but antisymmetric and transitive. The antisymmetry holds vacuously: no pair and are both present, so the condition never applies.
- a divides b on : look at the four properties yourself, and find the pair that decides symmetry. Then press the property name to outline it.
- same parity: reflexive, symmetric, transitive, so an equivalence relation with two classes.
- nothing (no pairs): symmetric, antisymmetric and transitive, all by emptiness, but not reflexive.
Worked examples
Four computations, each shown step by step with every set and every count taken from the same model as the stages. Step forward and back with the buttons; going back selects an earlier step, and nothing is undone.
Worked examples, step by step
Choose an example
Two open intervals. Open means the end is NOT included: A has every number strictly between 0 and 1, B every number strictly between 1 and 2.
Executable reference code
Run the Python examples below to follow the calculations step by step. The comments record what each line returns.
First the finite case, using Python’s built-in set: union |, intersection &, difference -, symmetric difference ^, the subset tests, De Morgan against an explicit universe, and ordered pairs from itertools.product. Notice that Python has no built-in complement: you must subtract from a universe you name.
from itertools import product
# A universe is a choice, not a given: a complement means nothing until you say "relative to U".
U = set(range(1, 13)) # {1, 2, ..., 12}
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
union = A | B # {1, 2, 3, 4, 5, 6, 7}
intersection = A & B # {4, 5}
a_minus_b = A - B # {1, 2, 3}
symmetric = A ^ B # {1, 2, 3, 6, 7}: in exactly one of the two
complement_a = U - A # {6, ..., 12}: always U minus the set
# Inclusion-exclusion: counting A and B separately counts A ∩ B twice.
inclusion_exclusion = len(union) == len(A) + len(B) - len(intersection) # True
# De Morgan: complementing swaps union and intersection.
de_morgan_union = (U - (A | B)) == (U - A) & (U - B) # True
de_morgan_intersection = (U - (A & B)) == (U - A) | (U - B) # True
# Subset tests: A <= B means every element of A is in B; < means proper subset.
a_in_b = A <= B # False (1 is not in B)
small_in_a = {2, 3} <= A # True
empty_is_subset = set() <= A # True: the empty set is a subset of every set
# Ordered pairs: (1, 2) and (2, 1) are different elements of a product.
X = {1, 2, 3}
Y = {3, 4}
pairs = set(product(X, Y)) # 3 * 2 = 6 ordered pairs
pairs_swapped = set(product(Y, X))
product_size_ok = len(pairs) == len(X) * len(Y) # True
commutes = pairs == pairs_swapped # False: X x Y is not Y x X unless X = Y or one is empty
# A relation on S is just a subset of S x S. Its properties are statements about that subset.
S = {1, 2, 3, 4}
less_than = {(a, b) for a, b in product(S, S) if a < b}
reflexive = all((a, a) in less_than for a in S) # False: 1 < 1 is false
transitive = all((a, c) in less_than for (a, b) in less_than for (b2, c) in less_than if b == b2) # True
same_parity = {(a, b) for a, b in product(S, S) if (a - b) % 2 == 0}
symmetric_parity = all((b, a) in same_parity for (a, b) in same_parity) # True
classes = {frozenset(b for b in S if (a, b) in same_parity) for a in S} # {frozenset({1, 3}), frozenset({2, 4})}
print(union, intersection, a_minus_b, symmetric, complement_a, inclusion_exclusion, de_morgan_union, de_morgan_intersection)
print(a_in_b, small_in_a, empty_is_subset, product_size_ok, commutes, reflexive, transitive, symmetric_parity, classes)Then intervals. Python has no interval type, so the file builds one from Fraction, which represents numbers like 0.1 exactly. It shows why a closed end must be tested on the exact number, when two intervals join, and the three empty cases from the Definition section.
from dataclasses import dataclass
from fractions import Fraction
# Closed endpoints are tests like x >= a. With doubles, 0.1 + 0.2 is not 0.3, so a closed test can fail by one rounding error.
double_sum = 0.1 + 0.2 # 0.30000000000000004
float_test = 0.3 <= double_sum <= 0.3 # False: the point 0.3 "missed" its own closed interval
# Fraction('0.1') reads the TEXT and gives exactly 1/10. Fraction(0.1) would read the double, which is not 1/10.
tenth, fifth = Fraction("0.1"), Fraction("0.2")
exact_test = Fraction("0.3") <= tenth + fifth <= Fraction("0.3") # True
@dataclass(frozen=True)
class Interval:
"""The set of x with lo <= x <= hi, each end open or closed. An infinite end is None and is always open."""
lo: Fraction | None
hi: Fraction | None
lo_closed: bool = True
hi_closed: bool = True
def contains(self, x: Fraction) -> bool:
above = self.lo is None or (x >= self.lo if self.lo_closed else x > self.lo)
below = self.hi is None or (x <= self.hi if self.hi_closed else x < self.hi)
return above and below
def is_empty(self) -> bool:
if self.lo is None or self.hi is None:
return False
return self.lo > self.hi or (self.lo == self.hi and not (self.lo_closed and self.hi_closed))
def touch_and_merge(left: Interval, right: Interval) -> bool:
"""Do two intervals with left.hi == right.lo form ONE interval? Only if the shared point belongs to at least one."""
return left.hi == right.lo and (left.hi_closed or right.lo_closed)
a = Interval(Fraction(0), Fraction(1), True, False) # [0, 1)
b = Interval(Fraction(1), Fraction(2), False, True) # (1, 2]
c = Interval(Fraction(1), Fraction(2), True, True) # [1, 2]
joined_ab = touch_and_merge(a, b) # False: 1 belongs to neither, so [0,1) ∪ (1,2] is two pieces
joined_ac = touch_and_merge(a, c) # True: [0,1) ∪ [1,2] = [0,2]
one_in_union = a.contains(Fraction(1)) or b.contains(Fraction(1)) # False
reversed_is_empty = Interval(Fraction(3), Fraction(1)).is_empty() # True: left end greater than right end
point_is_not_empty = Interval(Fraction(1), Fraction(1)).is_empty() # False: [1, 1] = {1}
open_point_is_empty = Interval(Fraction(1), Fraction(1), False, True).is_empty() # True: (1, 1] has nothing in it
print(double_sum, float_test, exact_test, joined_ab, joined_ac, one_in_union, reversed_is_empty, point_is_not_empty, open_point_is_empty)Finally the form the same ideas take on data: a split of row numbers into training, validation and test sets that must be disjoint, a Boolean mask as the indicator of a set, clipping to a closed interval, and a grid of combinations.
import numpy as np
# Rows of a dataset are indexed 0..9. A split into train / validation / test is three SETS of indices that must be disjoint.
rows = np.arange(10)
rng = np.random.default_rng(0)
order = rng.permutation(rows) # a shuffle of the indices
train, val, test = order[:6], order[6:8], order[8:]
disjoint = (
np.intersect1d(train, val).size == 0
and np.intersect1d(train, test).size == 0
and np.intersect1d(val, test).size == 0
) # True: no row appears in two splits (an overlap is "leakage")
covers = np.array_equal(np.union1d(np.union1d(train, val), test), rows) # True: together they are the whole universe
# Membership as a Boolean mask: np.isin(x, S) is the indicator 1[x in S], one entry per row.
mask_train = np.isin(rows, train) # array of True/False
indicator = mask_train.astype(int) # 0/1 values: 1 where the row is in the training set
count_matches = int(indicator.sum()) == train.size # True: summing the indicator counts the members
# Complement relative to the universe is the mask negation.
not_train = ~mask_train
complement_ok = np.array_equal(rows[not_train], np.union1d(val, test)) # True
# Clipping to a CLOSED interval [lo, hi]: values outside are moved onto the nearest endpoint, so the result is always in [lo, hi].
x = np.array([-3.0, 0.0, 0.5, 1.0, 4.0])
clipped = np.clip(x, 0.0, 1.0) # [0. 0. 0.5 1. 1. ]
inside = bool(np.all((clipped >= 0.0) & (clipped <= 1.0))) # True
# Cartesian product of two small feature value sets: every combination, as a grid of pairs.
first, second = np.meshgrid([0, 1, 2], [10, 20], indexing="ij")
grid = np.stack([first.ravel(), second.ravel()], axis=1) # 3 * 2 = 6 rows (a, b), a from the first set, b from the second
grid_size_ok = grid.shape == (3 * 2, 2) # True
print(disjoint, covers, count_matches, complement_ok, clipped, inside, grid_size_ok)Explore: change the sets
This is the finite stage with everything visible: the lists, the true-or-false facts about the pair, and the identities with your numbers in them. These questions have definite answers; check them against the stage.
Build two sets and combine them
Or start from
Show
A Venn diagram inside the universe U, the numbers 1 to 12, with two overlapping circles A and B. Only in A: 1, 2, 3. In both: 4, 5. Only in B: 6, 7. In neither: 8, 9, 10, 11, 12. Highlighted: union, {1, 2, 3, 4, 5, 6, 7}. The picture is schematic: the areas are not to scale.
Schematic: the areas are not to scale. The box is the universe U = {1, 2, …, 12}.
- elements in A
- 5
- elements in B
- 4
- union
- {1, 2, 3, 4, 5, 6, 7}
- elements in the result
- 7
= exact (every statement about finite sets is exact)
A ∪ B = {1, 2, 3, 4, 5, 6, 7}: everything that is in A, in B, or in both. It has 7 elements.
- A ⊆ B is false: 1 is in A but not in B.
- B ⊆ A is false: 6 is in B but not in A.
- A = B is false: neither contains the other.
- A ∩ B = ∅ is false: 2 elements in common: {4, 5}.
- Make the odd numbers from to and the even numbers from to (the disjoint preset). What is , and why does inclusion and exclusion collapse to a plain sum?
- Make and (the A inside B preset). What is ? What is ? What is , and what is ?
- Press A empty. Which operation gives the whole universe? Is a subset of , and is it a proper subset?
- Choose and and the operation . Count the elements. Then find, using the facts list, the two sides of De Morgan’s first law and check them against each other.
- Build two sets of your own where and are both true. What must be true of and ?
Common mistakes
Numerical considerations
Sets and intervals are exact: an element is in or it is not. Numbers on a computer are not. The decimal cannot be stored exactly in a double, and a closed end that is a decimal fraction can then miss itself.
Every interval value in this chapter is an exact decimal with at most two places, so the stage can say that an end is in or out with no doubt, and it writes . The same stage would be wrong to use for a computed double. A second place where a set meets a number: the empty set from reversed ends is not an error. The interval from to is empty because no satisfies ; code that sorts the ends silently, or clips them, answers a different question than the one that was asked. The stage reports that case with its reason instead of repairing it.
Finally, a finite set of floating-point numbers can contain two values that look the same when rounded for display and still compare different. Set membership uses exact equality, so 0.1 + 0.2 and 0.3 are two different elements of a Python set. When elements are measurements, round them to a stated precision first, or compare with a tolerance and use a structure that expects it.
Connections to engineering and machine learning
- Train, validation and test splits are disjoint sets. A split of the row numbers into three sets must satisfy , and the same for each other pair, and their union must be . If a row is in both train and test, the reported test score is optimistic: this is leakage. Counting the distinct rows is inclusion and exclusion: if , and ids are listed and exactly of them appear in both train and test, only different rows were used.
- An indicator is a set written as a column. The indicator of is the function that is on and elsewhere. In NumPy,
np.isin(rows, A)gives the Boolean mask, and summing the mask counts . The complement is the mask’s negation, the intersection is&and the union is|, which is why set algebra and mask algebra are the same algebra. - Clipping is intersection with a closed interval.
np.clip(x, lo, hi)moves every value outside onto the nearest end, so the result lies in the closed interval. The ends are included, and the choice of a closed interval matters: a clipped value of exactly is a legal output. - Feature spaces are products. A model that takes a colour from and a size from has combinations: the Cartesian product. A grid search over two hyperparameters is a product of two sets, and the cost is the product of the sizes, which is why adding one more parameter can multiply a run time rather than add to it.
- Equivalence relations are clustering. Grouping items into classes where being in the same class is reflexive, symmetric and transitive is a partition of the data. Duplicate detection is the same idea; if “is a near-duplicate of” is only close and not transitive, chaining gives classes you did not intend.
- A function is a relation with one output per input. A deterministic model is a function from inputs to outputs; a lookup table with two different outputs for the same key is a relation that is not a function, and the code that reads it must say which to use.
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.
Summary and checkpoints
- A set is determined by its elements: order and repeats do not matter. The union keeps what is in at least one set, the intersection what is in both, the difference what is in the first only, and a complement needs a named universe.
- Counting a union: . De Morgan: the complement of a union is the intersection of the complements, and the complement of an intersection is the union of the complements.
- An interval end is in (closed, filled dot) or out (open, hollow ring). Two touching intervals join into one piece exactly when the shared point is in at least one; is one point, and reversed ends or give the empty set. The complement of an interval flips every end.
- Ordered pairs keep their order. , and only if or one set is empty.
- A relation is a set of pairs. Reflexive, symmetric, antisymmetric and transitive are four separate properties, each with a witness when it fails. Reflexive, symmetric and transitive together make an equivalence relation, which splits a set into classes; a function is a relation with exactly one partner for each input.
- On a computer, exact membership needs exact numbers:
0.1 + 0.2is not0.3.
Checkpoints. You can move on when you can, without the stage:
- Say what , , and each keep, and count a union from three sizes.
- Decide whether is one interval, and whether is empty.
- Write the complement of and of in .
- List for two small sets and say why is different.
- Give a relation that is symmetric but not transitive, and one that is an equivalence relation, with its classes.