Ranges and edges in code
Why this matters
A model says "spam" when its score is at least 0.5. A learning rate must stay above 0. A batch of 32 rows is cut from a data set of 100. An index must wrap from the last item back to the first. Each of these is a rule about where a number sits against an edge, and each goes wrong the same small way: one edge is off by one. This lesson takes the symbols and the number line from the Foundation and turns them into code that is right at the edges: chained comparisons, half-open bands, slices and range(), what // and % do below zero, and clamping.
- Test for an interval with a chained comparison, and check it at its two edges
- Cut the number line into half-open bands with no gap and no overlap, in an if/elif chain, a slice and range()
- Predict // and % below zero, and use % to wrap an index or a clock around
- Clamp a value into a range with min and max, and see the same idea in np.clip and torch.clamp
age = 18 print(18 <= age < 25, 18 < age <= 25)
The idea: a number, an edge, and which side it falls on
This lesson rests on Inequalities and true-or-false (Foundation lesson 18), which gave the four symbols and the interval, and on Numbers below zero (Foundation lesson 4), which put the number line through zero. Here is the one thing from them that code needs: > and < leave the edge out, >= and <= keep it, and the opposite of x >= 50 is x < 50, never x <= 50. If you skipped them, this is the whole of it.