Piecewise and Absolute Value Functions
A piecewise function uses different formulas on different parts of its domain, exactly like an if/elif/else in code. Absolute value, rounding, tax brackets, clamping and the ReLU activation in neural networks are all piecewise functions. This lesson shows how to read, evaluate, graph and write them.
Definition and evaluation
To evaluate, find the piece whose condition contains , then use only that formula: , , . The conditions must not overlap (or must agree where they do), otherwise would not be a function.
The same thing in Python is an if chain. NumPy's np.piecewise or np.select and SymPy's Piecewise handle whole arrays or symbolic work:
import numpy as np
import sympy as sp
def f(x):
if x < -1:
return x + 3
elif x <= 2:
return x**2
else:
return 6 - x
print([f(v) for v in (-4, -1, 1, 2, 5)])
xs = np.array([-4.0, -1.0, 1.0, 2.0, 5.0])
print(np.piecewise(xs, [xs < -1, (xs >= -1) & (xs <= 2), xs > 2],
[lambda x: x + 3, lambda x: x**2, lambda x: 6 - x]))
x = sp.Symbol("x", real=True)
F = sp.Piecewise((x + 3, x < -1), (x**2, x <= 2), (6 - x, True))
pieces = [p for p, _ in F.args] # the three formulas
print("F(-1) =", F.subs(x, -1), " F(5) =", F.subs(x, 5))
print("at x = -1: left piece ->", pieces[0].subs(x, -1), ", middle piece ->", pieces[1].subs(x, -1))
print("at x = 2: middle piece ->", pieces[1].subs(x, 2), ", right piece ->", pieces[2].subs(x, 2))[-1, 1, 1, 4, 1]
[-1. 1. 1. 4. 1.]
F(-1) = 1 F(5) = 1
at x = -1: left piece -> 2 , middle piece -> 1
at x = 2: middle piece -> 4 , right piece -> 4
Note that and come from the middle piece, because its condition includes both endpoints. Plugging each break point into the neighbouring formulas tells us whether the pieces join up, which is the next topic.
Continuity at the break points
At each break point, compare the value from the left with the value from the right. If they match, the graph joins up; if not, it has a jump. Above, at the left piece approaches while the middle piece gives : a jump. At both sides give 4: the graph is continuous there. Making a piecewise function continuous by choosing a constant is a common exercise (and a common design task, see below). Continuity is defined precisely in Limits and Continuity.
Absolute value
The absolute value is the most important piecewise function:
It measures distance from 0, so is the distance between and on the number line. Its graph is a V with its vertex at the origin; moves the vertex to and scales the V by ( flips it). Equations and inequalities with absolute values turn into "two cases" or "between / outside" statements:
The Algebra course covers these in Absolute Value Equations and Compound Inequalities.
Step functions
A step function is constant on each piece and jumps between pieces.
| Function | Definition | Python |
|---|---|---|
| floor | the greatest integer | math.floor |
| ceiling | the smallest integer | math.ceil |
| Heaviside step | 0 for , 1 for | np.heaviside(x, 1) |
| sign | , 0 or 1 | np.sign |
Careful with negatives: , not . int(-2.5) in Python truncates toward zero and gives , which is a different function.
In software
Piecewise functions are everywhere in code, because every if creates one.
- if , if , if . Used for health bars, colour channels, scroll positions and the
acosargument in inverse trig. - , the default activation in deep neural networks. It is 0 for negative inputs and for positive ones: piecewise linear, continuous, with a corner at 0. Leaky ReLU uses instead of 0 on the left.
- Step and threshold functions: a pass/fail grade, a feature switching on above a load threshold,
x >= 0.5turning a probability into a class label. - Tax brackets and pricing tiers: the tax owed is a continuous piecewise linear function of income (each rate applies only to the part of income in its bracket), so earning one more dollar never loses you money.
import numpy as np
import matplotlib.pyplot as plt
clamp = lambda x, lo, hi: np.minimum(np.maximum(x, lo), hi)
relu = lambda x: np.maximum(0, x)
leaky = lambda x: np.where(x > 0, x, 0.1 * x)
x = np.linspace(-3, 3, 601)
fig, axes = plt.subplots(1, 4, figsize=(10, 2.8))
for ax, (name, y) in zip(axes, [("|x|", np.abs(x)), ("clamp(x, −1, 1.5)", clamp(x, -1, 1.5)),
("ReLU, leaky ReLU", relu(x)), ("floor(x)", np.floor(x))]):
ax.plot(x, y, color="purple", lw=2)
if name.startswith("ReLU"):
ax.plot(x, leaky(x), color="orange", ls="--")
ax.set_title(name, fontsize=9); ax.grid(alpha=0.3); ax.set_ylim(-3.2, 3.2)
fig.tight_layout()
v = np.array([-2.0, -0.5, 0.0, 0.7, 2.0])
print("relu :", relu(v))
print("clamp:", clamp(v, -1, 1.5))
print("floor:", np.floor(v), " int():", [int(t) for t in v])relu : [0. 0. 0. 0.7 2. ]
clamp: [-1. -0.5 0. 0.7 1.5]
floor: [-2. -1. 0. 0. 2.] int(): [-2, 0, 0, 0, 2]
A progressive tax, as a continuous piecewise linear function (made-up brackets):
BRACKETS = [(10_000, 0.00), (40_000, 0.10), (100_000, 0.20), (float("inf"), 0.35)]
def tax(income):
owed, lower = 0.0, 0.0
for upper, rate in BRACKETS:
if income > lower:
owed += (min(income, upper) - lower) * rate
lower = upper
return round(owed, 2)
for inc in (8_000, 40_000, 40_001, 100_000, 150_000):
print(f"{inc:>7}: tax {tax(inc):>9}") 8000: tax 0.0
40000: tax 3000.0
40001: tax 3000.2
100000: tax 15000.0
150000: tax 32500.0
At the bracket edge 40 000 the tax goes from 3000.0 to 3000.2 for one extra unit: continuous, only the slope changes.
Exercises
Exercise 1: Evaluate
For if , 3 if , if , find , , and .
Answer
, , 3, 6.
Solution
Exercise 2: Make it continuous
Find so that for and for is continuous.
Answer
.
Solution
The pieces must agree at : , so and . Check: both sides give 3.
import sympy as sp
k = sp.Symbol("k")
print(sp.solve(sp.Eq(2*k + 1, 4 - k), k))[1]
Exercise 3: Absolute value
Solve and .
Answer
or ; .
Solution
Exercise 4: Write without bars
Write as a piecewise function and find its minimum value.
Answer
for , 3 for , for . Minimum 3.
Solution
The break points are where the insides change sign: and .
Geometrically, is the sum of the distances from to 2 and to , which is smallest (3, the gap between them) when lies between them.
f = lambda x: abs(x - 2) + abs(x + 1)
print([f(x) for x in (-3, -1, 0, 2, 4)])[7, 3, 3, 3, 7]
Exercise 5: Smooth clamp vs hard clamp
Write clamp01(x) (hard clamp to ) and smoothstep(x) = 0 for , for , 1 for . Print both at .
Answer
clamp01: 0, 0.25, 0.5, 0.75, 1. smoothstep: 0, 0.15625, 0.5, 0.84375, 1.
Solution
def clamp01(x):
return 0.0 if x < 0 else 1.0 if x > 1 else x
def smoothstep(x):
t = clamp01(x)
return 3 * t**2 - 2 * t**3
xs = (-0.5, 0.25, 0.5, 0.75, 1.5)
print([clamp01(x) for x in xs])
print([smoothstep(x) for x in xs])[0.0, 0.25, 0.5, 0.75, 1.0]
[0.0, 0.15625, 0.5, 0.84375, 1.0]
smoothstep is built from the clamp plus a polynomial, and unlike the hard clamp it has no corners at 0 and 1 (its slope is 0 there), which is why shaders and animation code prefer it (easing curves).
Test yourself
What is ?
- 3
Which formula is ?
describes which set?
- or