TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Piecewise and Absolute Value Functions

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

f(x)={x+3if x<−1x2if −1≤x≤26−xif x>2f(x) = \begin{cases} x + 3 & \text{if } x < -1 \\ x^2 & \text{if } -1 \le x \le 2 \\ 6 - x & \text{if } x > 2 \end{cases}

To evaluate, find the piece whose condition contains xx, then use only that formula: f(−4)=−1f(-4) = -1, f(1)=1f(1) = 1, f(5)=1f(5) = 1. The conditions must not overlap (or must agree where they do), otherwise ff 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:

python · try it yourself
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 f(−1)=1f(-1) = 1 and f(2)=4f(2) = 4 come from the middle piece, because its condition −1≤x≤2-1 \le x \le 2 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 x=−1x = -1 the left piece approaches −1+3=2-1 + 3 = 2 while the middle piece gives (−1)2=1(-1)^2 = 1: a jump. At x=2x = 2 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:

∣x∣={xif x≥0−xif x<0\lvert x \rvert = \begin{cases} x & \text{if } x \ge 0 \\ -x & \text{if } x < 0 \end{cases}

It measures distance from 0, so ∣a−b∣\lvert a - b \rvert is the distance between aa and bb on the number line. Its graph is a V with its vertex at the origin; y=a∣x−h∣+ky = a\lvert x - h \rvert + k moves the vertex to (h,k)(h, k) and scales the V by aa (a<0a < 0 flips it). Equations and inequalities with absolute values turn into "two cases" or "between / outside" statements:

∣x−3∣=5  ⟺  x−3=5 or x−3=−5  ⟺  x=8 or x=−2∣x−3∣<5  ⟺  −5<x−3<5  ⟺  −2<x<8∣x−3∣>5  ⟺  x<−2 or x>8\begin{aligned} \lvert x - 3 \rvert = 5 &\iff x - 3 = 5 \text{ or } x - 3 = -5 &&\iff x = 8 \text{ or } x = -2 \\ \lvert x - 3 \rvert < 5 &\iff -5 < x - 3 < 5 &&\iff -2 < x < 8 \\ \lvert x - 3 \rvert > 5 &\iff x < -2 \text{ or } x > 8 \end{aligned}

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 ⌊x⌋\lfloor x \rfloor the greatest integer ≤x\le x math.floor
ceiling ⌈x⌉\lceil x \rceil the smallest integer ≥x\ge x math.ceil
Heaviside step H(x)H(x) 0 for x<0x < 0, 1 for x≥0x \ge 0 np.heaviside(x, 1)
sign sgn⁡(x)\operatorname{sgn}(x) −1-1, 0 or 1 np.sign

Careful with negatives: ⌊−2.5⌋=−3\lfloor -2.5 \rfloor = -3, not −2-2. int(-2.5) in Python truncates toward zero and gives −2-2, which is a different function.

In software

Piecewise functions are everywhere in code, because every if creates one.

  • clamp⁡(x,lo,hi)\operatorname{clamp}(x, \text{lo}, \text{hi}) =lo= \text{lo} if x<lox < \text{lo}, xx if lo≤x≤hi\text{lo} \le x \le \text{hi}, hi\text{hi} if x>hix > \text{hi}. Used for health bars, colour channels, scroll positions and the acos argument in inverse trig.
  • ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x) = \max(0, x), the default activation in deep neural networks. It is 0 for negative inputs and xx for positive ones: piecewise linear, continuous, with a corner at 0. Leaky ReLU uses 0.01x0.01x instead of 0 on the left.
  • Step and threshold functions: a pass/fail grade, a feature switching on above a load threshold, x >= 0.5 turning 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.
python · try it yourself
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):

python · try it yourself
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 g(x)=2x−1g(x) = 2x - 1 if x≤0x \le 0, 3 if 0<x<40 < x < 4, x2−10x^2 - 10 if x≥4x \ge 4, find g(−2)g(-2), g(0)g(0), g(3.9)g(3.9) and g(4)g(4).

Answer

−5-5, −1-1, 3, 6.

Solution
g(−2)=2(−2)−1=−5(first piece)g(0)=2(0)−1=−1(first piece: x≤0)g(3.9)=3(middle piece)g(4)=16−10=6(last piece: x≥4)\begin{aligned} g(-2) &= 2(-2) - 1 = -5 && \text{(first piece)} \\ g(0) &= 2(0) - 1 = -1 && \text{(first piece: } x \le 0\text{)} \\ g(3.9) &= 3 && \text{(middle piece)} \\ g(4) &= 16 - 10 = 6 && \text{(last piece: } x \ge 4\text{)} \end{aligned}

Exercise 2: Make it continuous

Find kk so that h(x)=kx+1h(x) = kx + 1 for x<2x < 2 and h(x)=x2−kh(x) = x^2 - k for x≥2x \ge 2 is continuous.

Answer

k=1k = 1.

Solution

The pieces must agree at x=2x = 2: 2k+1=4−k2k + 1 = 4 - k, so 3k=33k = 3 and k=1k = 1. Check: both sides give 3.

python · try it yourself
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 ∣2x+1∣=7\lvert 2x + 1 \rvert = 7 and ∣2x+1∣≤7\lvert 2x + 1 \rvert \le 7.

Answer

x=3x = 3 or x=−4x = -4; −4≤x≤3-4 \le x \le 3.

Solution
2x+1=7⇒x=32x+1=−7⇒x=−4−7≤2x+1≤7⇒−8≤2x≤6⇒−4≤x≤3\begin{aligned} &2x + 1 = 7 \Rightarrow x = 3 \qquad 2x + 1 = -7 \Rightarrow x = -4 \\ &-7 \le 2x + 1 \le 7 \quad\Rightarrow\quad -8 \le 2x \le 6 \quad\Rightarrow\quad -4 \le x \le 3 \end{aligned}

Exercise 4: Write ∣x−2∣+∣x+1∣\lvert x - 2 \rvert + \lvert x + 1 \rvert without bars

Write f(x)=∣x−2∣+∣x+1∣f(x) = \lvert x - 2 \rvert + \lvert x + 1 \rvert as a piecewise function and find its minimum value.

Answer

f(x)=−2x+1f(x) = -2x + 1 for x<−1x < -1, 3 for −1≤x≤2-1 \le x \le 2, 2x−12x - 1 for x>2x > 2. Minimum 3.

Solution

The break points are where the insides change sign: x=−1x = -1 and x=2x = 2.

x<−1:−(x−2)−(x+1)=−2x+1−1≤x≤2:−(x−2)+(x+1)=3x>2:(x−2)+(x+1)=2x−1\begin{aligned} x < -1{:} &\quad -(x - 2) - (x + 1) = -2x + 1 \\ -1 \le x \le 2{:} &\quad -(x - 2) + (x + 1) = 3 \\ x > 2{:} &\quad (x - 2) + (x + 1) = 2x - 1 \end{aligned}

Geometrically, f(x)f(x) is the sum of the distances from xx to 2 and to −1-1, which is smallest (3, the gap between them) when xx lies between them.

python · try it yourself
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 [0,1][0, 1]) and smoothstep(x) = 0 for x<0x < 0, 3x2−2x33x^2 - 2x^3 for 0≤x≤10 \le x \le 1, 1 for x>1x > 1. Print both at x=−0.5,0.25,0.5,0.75,1.5x = -0.5, 0.25, 0.5, 0.75, 1.5.

Answer

clamp01: 0, 0.25, 0.5, 0.75, 1. smoothstep: 0, 0.15625, 0.5, 0.84375, 1.

Solution
python · try it yourself
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.2⌋\lfloor -3.2 \rfloor?

  1. −3-3
  2. −4-4
  3. 3
  4. −3.2-3.2

Which formula is ReLU⁡(x)\operatorname{ReLU}(x)?

  1. ∣x∣\lvert x \rvert
  2. max⁡(0,x)\max(0, x)
  3. min⁡(0,x)\min(0, x)
  4. 1 if x≥0 else 01 \text{ if } x \ge 0 \text{ else } 0

∣x−5∣<2\lvert x - 5 \rvert < 2 describes which set?

  1. x<7x < 7
  2. 3<x<73 < x < 7
  3. x<3x < 3 or x>7x > 7
  4. −7<x<−3-7 < x < -3